仅在字符串中查找整数

Find whole number only in string

想要获取字符串中的第一个整数或字符串中单词之前的数字。

例如

string input = "hello 123.45 789 coins";

要忽略 123.45,只将 789 转换为 int。

使用正则表达式

\d+(?![0-9.])

说明

  • \d匹配一个数字(相当于[0-9])
  • + 匹配前一个令牌一次到无限次,尽可能多次,按需回馈
  • 负面展望(?![0-9.])。正则表达式不匹配匹配下面列表中的单个字符
  • [0-9.]0-9匹配0到9范围内的单个字符,
  • . 字面匹配索引为 4610 的字符 (.)(区分大小写)
  • m修饰符:多行。使 ^ 匹配每一行的 begin/end

一些正则表达式就足够了,或者像这样简单的东西:

var valueString = "hello 123.45 789 coins REE";

var words = valueString.Split(' ');

for (var index = 0; index < words.Length-1 ; index++) // words.Length-1 so the last item is skipped 
{
    var word = words[index];
    var nextWord  = words[index+1]; // optionally check if the next word is an int or not?

    if (int.TryParse(word, NumberStyles.Integer, CultureInfo.InvariantCulture, out var valueInt))
    {
        Console.WriteLine(valueInt);
    }
}