从MatchCollection C#获取完整的单词

时间:2016-12-25 17:29:15

标签: c# regex match

我认为A 1A 12A 123A 1234B 1B 12B 123相同,B 1234其中123表示三位数 现在,当我这样做时:

MatchCollection ForA1 = Regex.Matches(inFile, @"\b(A [0-9])\b");
MatchCollection ForA2 = Regex.Matches(inFile, @"\b(A [0-9][0-9])\b");
.... and so on for three and four digits and B; total 8 lines

减少我执行此操作的代码:

MatchCollection ForAB1 = Regex.Matches(inFile, @"\b(A [0-9]|B [0-9])\b");
MatchCollection ForAB2 = Regex.Matches(inFile, @"\b(A [0-9][0-9]|B [0-9][0-9])\b");
.... and so on for three and four digits; total 4 lines

现在我想这样做:

MatchCollection ForAB1234 = Regex.Matches(inFile, @"\b(A [0-9]|B [0-9]...
|A [0-9][0-9]|B [0-9][0-9] and so on for three and four digits )\b"); total 1 line

在比赛后的这个时间我这样做:

foreach (Match m in ForAB1)
   {
     //many calculations on the basis of index and length etc
     }

我想要的是什么:

foreach (Match m in ForAB1)
   {
     if(Match is 'A [0-9]')
     {//many calculations on the basis of index and length etc}
     else...
   }

有没有其他简单的东西,以便我不需要仅仅因为不同的位数而重复代码?我正在寻找我用过的所有不同的比赛。

编辑:真正的问题是我不想m.len然后检查它是A还是B,因为实际上我有超过30个这样的表达

1 个答案:

答案 0 :(得分:2)

要确保只检查A 1类型而不是A 11类型,您需要使用类似

的内容
foreach (Match m in ForAB1)
 {
     if (Regex.IsMatch(m.Value, @"^A [0-9]$"))
     {//many calculations on the basis of index and length etc}
     else if (Regex.IsMatch(m.Value, @"^A [0-9]{2}$"))
     {//many calculations on the basis of index and length etc}
     else...
 }