从字符串中获取第一个数字

本文关键字:第一个 数字 获取 字符串 | 更新日期: 2023-09-27 18:33:45

我想获取字符串中数字的第一个实例。

所以我得到了这个输入字符串,可能是以下之一:

1: "Event: 1 - Some event"
2: "Event 12 -"
3: "Event: 123"
4: "Event: 12 - Some event 3"

输入字符串的输出必须是:

1: 1
2: 12
3: 123
4: 12

我尝试了以下方法,但没有一种方法能准确地给我想要的东西。

number = new String(input.ToCharArray().Where(c => Char.IsDigit(c)).ToArray());
//This gives me all the numbers in the string
var index = input.IndexOfAny("0123456789".ToCharArray());
string substring = input.Substring(index, 4);
number = new string(substring.TakeWhile(char.IsDigit).ToArray());
//This gives me first number and then the numbers in the next 4 characters. However it breaks if there is less than 4 characters after the first number.

编辑:很多人发布了很好的解决方案,但我最终接受了我在代码中实际使用的解决方案。我希望我能接受更多的答案!

从字符串中获取第一个数字

使用 Linq 执行此操作的正确方法如下

number = new string(input.SkipWhile(c=>!char.IsDigit(c))
                         .TakeWhile(c=>char.IsDigit(c))
                         .ToArray());

基本上跳过所有不是数字的内容,然后在它们不再是数字时停止使用字符。 请注意,这将在标点符号处停止,因此它不会从字符串中提取类似"30.5"的内容。 如果您需要处理数字中的标点符号,那么正则表达式将是要走的路。 另请注意,您不需要执行ToCharArray因为字符串实现IEnumerable<char>这是 Linq 所需的全部内容。

此外,您还必须面向 .Net 4.0,因为这是他们添加 SkipWhileTakeWhile扩展方法时。

在我看来

,你只需要一个正则表达式:

using System;
using System.Text.RegularExpressions;
public class Test
{
    static void Main()
    {
        ExtractFirstNumber("Event: 1 - Some event");
        ExtractFirstNumber("Event: 12 -");
        ExtractFirstNumber("Event: 123");
        ExtractFirstNumber("Event: 12 - Some event 3");
        ExtractFirstNumber("Event without a number");
    }
    private static readonly Regex regex = new Regex(@"'d+");
    static void ExtractFirstNumber(string text)
    {
        var match = regex.Match(text);
        Console.WriteLine(match.Success ? match.Value : "No match");
    }
}
第一个

匹配项将仅从第一个数字开始,并将在第一个非数字(或字符串的末尾)停止。如果需要,可以使用匹配项的LengthIndex属性来确定它在字符串中的位置。

see if this helps
 var input = "sdmfnasldkfjhasdlfkjh234sdf234234";
        var index = input.IndexOfAny("0123456789".ToCharArray());
        string substring = input.Substring(index); // this will give rest of the string.
        number = new string(substring.TakeWhile(char.IsDigit).ToArray());
        //number will have 234

使用正则表达式获取结果。

有关正则表达式的更多详细信息,请参阅此内容。

    String s1= "Event: 1 - Some event";
    String s2=  "Event 12 -";
    String s3= "Event: 123";
    String s4=  "Event: 12 - Some event 3";

    String result1 = System.Text.RegularExpressions.Regex.Match(s1, @"'d+").Value;
    String result2 = System.Text.RegularExpressions.Regex.Match(s2, @"'d+").Value;
    String result3 = System.Text.RegularExpressions.Regex.Match(s3, @"'d+").Value;
    String result4 = System.Text.RegularExpressions.Regex.Match(s4, @"'d+").Value;