8

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

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

How can I extract separate numbers like "1920" and "1080" from it, assuming they will just be separated by one or more non-numeric character(s)?

David
  • 15,652
  • 26
  • 115
  • 156
  • Please decide which language you need the answer in. The regex objects in .NET are not the same as the Java ones. – Oded May 31 '12 at 11:06

4 Answers4

12

The basic regular expression would be:

[0-9]+

You will need to use the library to go over all 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
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
5

You can get the string by following

MatchCollection v = Regex.Matches(input, "[0-9]+");
foreach (Match s in v)
            {
                // output is s.Value
            }
Md Kamruzzaman Sarker
  • 2,387
  • 3
  • 22
  • 38
1
(\d+)\D+(\d+)

After that, customize this regex to match the flavour of the language you'll be using.

dda
  • 6,030
  • 2
  • 25
  • 34
  • `\d` will contain _all_ digits, not only roman numerals, depending on regex library and platform. – Oded May 31 '12 at 11:08
  • .net / C#'s (and PCRE's) regex `\d` matches [0-9]. Period. – dda May 31 '12 at 11:13
  • No, it doesn't. It will match on ٠١٢٣٤٥٦٧٨٩ - http://stackoverflow.com/a/6479605/1583 – Oded May 31 '12 at 11:15
  • If the character is defined as a Unicode digit, it will be matched in .NET by `\d`. – Oded May 31 '12 at 11:18
  • 1
    Could you explain the advantage of this over Regex.Matches(s, "[0-9]+");? – David May 31 '12 at 11:22
  • 1
    @Oded Your first comment confused me until I realised that you didn't mean `I`, `II`, ... `VII` etc. Aren't 0-9 Arabic? – Rawling May 31 '12 at 11:22
  • @Rawling - Yes, they are. Badly put by myself. Meant the digits normally used in the west, versus other scripts. – Oded May 31 '12 at 11:25
1

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
Damith
  • 62,401
  • 13
  • 102
  • 153