【问题标题】:named capture group in regex正则表达式中的命名捕获组
【发布时间】:2011-10-26 18:12:22
【问题描述】:

我需要正则表达式的帮助来从以下字符串中捕获数字和连字符: “一些文字和东西 200-1234EM 一些其他东西”

它也可以不带连字符的部分出现: "一些文字 123EM 其他文字"

我需要命名捕获组中的“200-1234”或“123”。

我试过这个: \b([0-9]{0,3}\-{0,1}[0-9]{3})EM\b

确实匹配,但不是命名组。

当我尝试这样命名组时: \b(?<test>[0-9]{0,3}\-{0,1}[0-9]{3})EM\b 我收到一条错误消息“索引 34 附近的未知后视组”

我需要它在 .NET RegEx 类中工作

谢谢!

【问题讨论】:

  • 你在哪里测试这个?虽然正则表达式不正确(请参阅@FailedDev 的正确答案),但命名组语法对于 .NET 是正确的。
  • 对我来说也是如此,在 regex-tester 中使用 wwww.regexlib.com 上的 silverlight 测试器
  • 你确定它失败的是同一个正则表达式吗?您的正则表达式没有后视。
  • @Alan:我使用了一些基于 Java 的愚蠢在线测试器,因此存在命名问题。感谢 regexlib.com 的提示,他们的 silverlight 测试仪很好

标签: .net regex


【解决方案1】:
resultString = Regex.Match(subjectString, @"\b(?<number>\d+(?:-\d+)?)EM\b").Groups["number"].Value;

这应该可以解决问题。如果您提供更多输入,我可以使它更健壮。

说明:

    @"
\b            # Assert position at a word boundary
(?<number>    # Match the regular expression below and capture its match into backreference with name “number”
   \d            # Match a single digit 0..9
      +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   (?:           # Match the regular expression below
      -             # Match the character “-” literally
      \d            # Match a single digit 0..9
         +             # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   )?            # Between zero and one times, as many times as possible, giving back as needed (greedy)
)
EM            # Match the characters “EM” literally
\b            # Assert position at a word boundary
"

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2014-10-27
    • 2021-04-16
    • 2019-01-18
    相关资源
    最近更新 更多