查找字符串中的第一个整数或字符串中单词之前的数字。
例如
string input = "hello 123.45 789 coins";忽略123.45并仅将789转换为int。
发布于 2021-12-20 09:37:02
一些regex就足够了,或者有些很简单,比如:
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);
}
}发布于 2021-12-20 09:36:48
使用Regex表达式
\d+(?![0-9.])解释
\d匹配一个数字(相当于0-9)+在一次和无限次之间匹配前一个令牌,尽可能多次,返回needed(?![0-9.])。Regex不匹配列表中的单个字符,below[0-9.] 0-9匹配0到9之间的单个字符,.匹配字符(.)使用索引4610字面上(区分大小写)的开始/结束。
https://stackoverflow.com/questions/70419732
复制相似问题