Reputation: 16028
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)?
Upvotes: 8
Views: 19529
Reputation: 63065
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
Upvotes: 1
Reputation: 2407
You can get the string by following
MatchCollection v = Regex.Matches(input, "[0-9]+");
foreach (Match s in v)
{
// output is s.Value
}
Upvotes: 5
Reputation: 498934
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
}
Upvotes: 12
Reputation: 6203
(\d+)\D+(\d+)
After that, customize this regex to match the flavour of the language you'll be using.
Upvotes: 1