-6

我需要一些帮助来找到适合我需要的正则表达式,我想要的是输入可能是任何字符串,正则表达式找到任何和所有整数值并返回它们,比如说

string s1 = "This is some string"
string s2 = " this is 2 string"
string s3 = " this is 03 string"
string s4 = "4 this is the 4th string"
string s5 = "some random string: sakdflajdf;la  989230"
string s6 = "3494309 !@# 234234"

现在我想要的是正则表达式返回,

for s1 = return null (// nothing)
s2 = return 2
s3 = return 0 and 3 (// may separately as 0 and 3 or together as 03 doesn't matter)
s4 = return 4 and 4 (// it has 4 2 times right?)
s5 = 989230 (// may together as this or separately as 9 8 9 2 3 0 again is unimportant, but what's important is that it should return all integer values)
s6 = 3494309 and 234234 (// again may they be together as this or like this 3 4 9 4 3 0 9 and 2 3 4 2 3 4 that is unimportant, all that is imp is that it should return all integers)

我已经尝试过[0-9]\d^.*[0-9]+.*$但它们似乎都不起作用。有人可以帮忙吗?

ps:请参阅使用正则表达式重命名文件中的更新问题

4

2 回答 2

9

连续匹配一个或多个数字的正则表达式是:

\d+

你可以这样应用它:

Regex.Matches(myString, @"\d+")

这将返回一个MatchCollection对象集合。这将包含匹配的值。

你可以像这样使用它:

var matches = Regex.Matches(myString, @"\d+");

if (matches.Count == 0)
  return null;

var nums = new List<int>();
foreach(var match in matches)
{
  nums.Add(int.Parse(match.Value));
}

return nums;
于 2012-04-11T20:02:21.200 回答
2

我知道这看起来有点容易,但我认为\d会做你想做的

我知道你说过你试过这个......要小心的一件事是,如果你使用字符串来表示这一点,你需要忽略转义

var pattern = @"\d+";
于 2012-04-11T20:03:42.100 回答