正则表达式 - 查找由空格和彗差包围的每个整数

时间:2014-07-31 12:30:17

标签: c# regex

我有以下字符串:

"121 fd412 4151 3213, 421, 423 41241 fdsfsd"

我需要得到3213和421 - 因为他们前面都有空间,后面有昏迷。

结果将在字符串数组中设置...我该怎么做?

"\\d+"捕获每个整数。

"\s\\d+(,)"会引发一些内存错误。

EDIT。

数字左侧(<-)的空格,右侧的昏迷(->)

编辑2。

string mainString = "Tests run: 5816, 8346, 28364 iansufbiausbfbabsbo3 4";
MatchCollection c = Regex.Matches(a, @"\d+(?=\,)");
var myList = new List<String>();
foreach(Match match in c)
{
    myList.Add(match.Value);
}            
Console.Write(myList[1]);
Console.ReadKey();

6 个答案:

答案 0 :(得分:4)

您想要匹配两个数字的正则表达式语法不正确,如果您希望它们作为单独的结果,您可以这样做:

@"\s(\d+),\s(\d+)\s"

Live Demo

修改

@"\s(\d+),"

Live Demo

答案 1 :(得分:0)

\s\\d+(,)

  • \s未正确转义,应为\\s,与\\d相同
  • \\d匹配单个数字,您需要\\d+ - 一个或多个连续数字
  • (,)捕获逗号,你真的需要这个吗?好像你需要捕获一个数字,所以\\s(\\d+),
  • 你说“因为他们背后都有空间,前面有昏迷”,所以可能,\\s(\\d+)

答案 2 :(得分:0)

这个表达怎么样:

 " \d+,"  // expression without the quotes

它应该找到你需要的东西。

如何使用正则表达式,您可以查看MSDN

希望有所帮助

答案 3 :(得分:0)

我认为你的意思是说你正在寻找像,<space><digit>而不是,<digit><space>

这样的东西

如果有,请尝试this

, (\d+)   //you might need to add another backslash as the others have noted

好吧,根据你的新编辑

\s(\d+),

测试here

答案 4 :(得分:0)

这就是你所需要的,只有数字

\d+(?=\,)

regex

Console

答案 5 :(得分:0)

另一种解决方案

\s(\d+),  // or maybe you'll need a double slash \\

输出:

3213
421

Demo