首页 > 解决方案 > 尝试使用 LINQ 仅过滤字符串数组中的数字

问题描述

我正在尝试仅过滤字符串数组中的数字。如果我有这个数组:12324 asddd 123 123,这可以工作,但如果我在一个字符串中有字符和数字,例如 asd1234,它不会接受它。你能帮我怎么做吗?

int[] result = input
            .Where(x => x.All(char.IsDigit))// tried with .Any(), .TakeWhile() and .SkipWhile()
            .Select(int.Parse)
            .Where(x => x % 2 == 0)
            .ToArray();

标签: c#linq

解决方案


如果我在一个字符串中包含字符和数字,例如 asd1234,它不会接受它

显然你也想解析这一行。您想将“asd1234”翻译成“1234”,然后解析它。

但是,如果您的输入字符串序列包含一个带有两个数字的字符串:“123asd456”。您想将其解释为“123”,还是“123456”,或者您将其视为两个数字“123”和“456”。

假设您没有这个问题:每个字符串最多包含一个数字,或者如果您有一个包含多个数字的字符串,您只需要第一个数字。

实际上,您只想保留那些“零个或多个非数字后跟一个或多个数字后跟零个或多个字符”的字符串。

输入正则表达式!

const string regexTxt = "\D*\d+.*";
Regex regex = new Regex(regexTxt);
  • \D:任何非数字
  • *:零个或多个
  • \d:任何数字
  • +:一个或多个
  • . 任何字符
  • (...) 捕获括号之间的部分

所以这个正则表达式匹配任何以零个或多个非数字开头,后跟至少一个数字,后跟零个或多个字符的字符串。捕获“至少一位数字”部分。

如果您尝试Match()使用此正则表达式输入字符串,则会得到一个Match对象。属性Success告诉你输入的字符串是否符合正则表达式。

Match对象有一个Groups包含所有匹配项的属性。Groups[0] 是完整的字符串,Groups 1包含一个Group在 property 中具有第一个捕获的字符串的a Value

一个简单的程序,展示了如何使用正则表达式:

const string regexTxt = @"\D*(\d+).*";
Regex regex = new Regex(regexTxt);
var lines = new string[]
{
    String.Empty,
    "A",
    "A lot of text, no numbers",
    "1",
    "123456",
    "Some text and then a number 123",
    "Several characters, then a number: 123 followed by another number 456!",
    "___123---456...",
};
foreach (var line in lines)
{
    Match match = regex.Match(line);
    if (match.Success)
    {
         string capturedDigits = match.Groups[1].Value;
         int capturedNumber = Int32.Parse(capturedDigits);
         Console.WriteLine("{0} => {1}", line, capturedNumber);
    }
}

或者在 LINQ 语句中:

const string regexTxt = @"\D*(\d+).*";
Regex regex = new Regex(regexTxt);
IEnumerable<string> sourceLines = ...
var numbers= sourceLines
    .Select(line => regex.Match(line))      // Match the Regex
    .Where(match => match.IsMatch)          // Keep only the Matches that match
    .Select(match => Int32.Parse(match.Groups[1].Value);
                                            // Finally Parse the captured text to int

推荐阅读