webdad3
webdad3

Reputation: 9080

Returning all numbers in regular expression

I'm trying to find all the hard coded IDs that have been put in the application. I've created a console app that I'm trying to find all the IDs. I'm running into several issues.

I have a lot of different formats that I'm trying to find but I figure I'll do 1 at a time for now:

For example I have the following:

if ((Id != "28" && Id != "29" && Id != "9" && Id != "123" && Id != "904"))

This only returns "9"

Match match = Regex.Match(line, "Id != \"[0-9]\"",  RegexOptions.IgnoreCase);

if (match.Success) {
    string key = match.Groups[0].Value;
    Console.WriteLine(key);
}

I would like to know how I can return every number found in my example above. I would like to return:

Upvotes: 2

Views: 56

Answers (2)

Steve
Steve

Reputation: 11963

you should call .Matches

MatchCollection matches = Regex.Matches(line, "Id != \"([0-9]+)\"",  RegexOptions.IgnoreCase);

foreach(Match match in matches)
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You need to match one or more digit, and either call Matches to get all matches, or call next match to continue the search:

Match match = Regex.Match(line, "Id != \"([0-9]+)\"",  RegexOptions.IgnoreCase);

while (match.Success) {
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
    match = match.NextMatch();
}

The changes from your code are as follows:

  • Replaced [0-9] with ([0-9]+)
  • Switched to using Groups[1] from Groups[0] to ignore the irrelevant parts
  • Added a loop and a call to NextMatch().

Demo.

Upvotes: 2

Related Questions