繁体   English   中英

使用正则表达式从字符串中提取多个数字

[英]Using regex to extract multiple numbers from strings

我有一个包含两个或更多数字的字符串。 这里有一些例子:

"(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<string> uniqueNumbers = new HashSet<string>();
foreach (Match m in matches)
{
    uniqueNumbers.Add(m.Groups[1].Value);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM