Using regex to extract multiple numbers from strings

I have a string with two or more numbers. Here are some examples:

"(1920x1080)" " 1920 by 1080" "16 : 9" 

How can I extract individual digits from it, such as “1920” and “1080”, if they are simply separated by one or more non-numeric characters?

+7
source share
5 answers

The main regex will be:

 [0-9]+ 

You will need to use the library to go through all the matches and get their values.

 var matches = Regex.Matches(myString, "[0-9]+"); foreach(var march in matches) { // match.Value will contain one of the matches } 
+9
source

You can get the string by following

 MatchCollection v = Regex.Matches(input, "[0-9]+"); foreach (Match s in v) { // output is s.Value } 
+5
source
 (\d+)\D+(\d+) 

After that, tweak this regex to match the taste of the language you will use.

+1
source

you can use

 string[] input = {"(1920x1080)"," 1920 by 1080","16 : 9"}; foreach (var item in input) { var numbers = Regex.Split(item, @"\D+").Where(s => s != String.Empty).ToArray(); Console.WriteLine("{0},{1}", numbers[0], numbers[1]); } 

OUTPUT:

 1920,1080 1920,1080 16,9 
+1
source

There is still a problem, but all of the above answers consider 12i or a2 to be real numbers when they shouldn't.

The following issues may resolve this issue.

 var matches = Regex.Matches(input, @"(?:^|\s)\d+(?:\s|$)"); 

But this solution adds another problem :) This will capture the spaces around the integer. To solve this, we need to fix the value of the integer into the group:

 MatchCollection matches = Regex.Matches(_originalText, @"(?:^|\s)(\d+)(?:\s|$)"); HashSet<string> uniqueNumbers = new HashSet<string>(); foreach (Match m in matches) { uniqueNumbers.Add(m.Groups[1].Value); } 
0
source

All Articles