【问题标题】:Get full word from MatchCollection C# not group从 MatchCollection C# 中获取完整的单词而不是组
【发布时间】:2017-05-10 10:34:43
【问题描述】:

假设A 1A 12A 123A 1234B 1B 12B 123B 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 这个问题应该有适当的理由,我认为你可以在这里写

标签: c# regex match


【解决方案1】:

为了确保您只检查 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...
 }

【讨论】:

  • 出现不是问题 我已经有 MatchCollection 可以查找尽可能多的出现。我正在寻找我通过管道传输的所有不同的匹配项
  • 那你为什么用\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 不是问题匹配确实有效。问题在foreach 循环内我想做一件事,如果匹配是 A 1,另一件事如果匹配是 A 11,就像 (type1|type2) 在正则表达式内,现在我想在 MatchCollection 中查看,如果选择的是 type1 或 type2
  • 那么,用^$ 封装这些模式有用吗?
  • 有什么不同?
猜你喜欢
  • 1970-01-01
  • 2012-10-13
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
相关资源
最近更新 更多