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)?

1
  • Please decide which language you need the answer in. The regex objects in .NET are not the same as the Java ones. Commented May 31, 2012 at 11:06

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

5

You can get the string by following

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

3 Comments

RegexOptions.IgnoreCase is not needed. Roman numerals don't have upper/lower cases.
Normally i practice with RegexOptions.IgnoreCase. Sorry for mistake
Not a mistake as such. Just not needed in this case.
1
(\d+)\D+(\d+)

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

7 Comments

\d will contain all digits, not only roman numerals, depending on regex library and platform.
.net / C#'s (and PCRE's) regex \d matches [0-9]. Period.
No, it doesn't. It will match on ٠١٢٣٤٥٦٧٨٩ - stackoverflow.com/a/6479605/1583
Could you explain the advantage of this over Regex.Matches(s, "[0-9]+");?
@Oded Your first comment confused me until I realised that you didn't mean I, II, ... VII etc. Aren't 0-9 Arabic?
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.