使用正则表达式从字符串中提取多个数字
我有一个包含两个或更多数字的字符串。 这里有一些例子:
"(1920x1080)" " 1920 by 1080" "16 : 9"
如何从中提取单独的数字,如“1920”和“1080”,假设它们只是由一个或多个非数字字符分隔?
基本的正则表达式是:
[0-9]+
您将需要使用该库来检查所有匹配并获取其值。
var matches = Regex.Matches(myString, "[0-9]+"); foreach(var march in matches) { // match.Value will contain one of the matches }
您可以通过以下方式获取字符串
MatchCollection v = Regex.Matches(input, "[0-9]+"); foreach (Match s in v) { // output is s.Value }
(\d+)\D+(\d+)
之后,自定义此正则表达式以匹配您将使用的语言的风格。
您可以使用
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
但仍然存在一个问题,所有上述答案都应考虑12i或a2有效数字。
以下可以解决此问题
var matches = Regex.Matches(input, @"(?:^|\s)\d+(?:\s|$)");
但是这个解决方案又增加了一个问题:)这将捕获整数周围的空格。 为了解决这个问题,我们需要将整数的值捕获到一个组中:
MatchCollection matches = Regex.Matches(_originalText, @"(?:^|\s)(\d+)(?:\s|$)"); HashSet uniqueNumbers = new HashSet (); foreach (Match m in matches) { uniqueNumbers.Add(m.Groups[1].Value); }