简体   繁体   English

正则表达式中的命名捕获组

[英]named capture group in regex

I need help with a regex to capture the numbers and hyphen from the following string: "some text and stuff 200-1234EM some other stuff" 我需要正则表达式的帮助,才能从以下字符串中捕获数字和连字符:“某些文本和内容200-1234EM其他内容”

It can also appear without the hypenated part: "some text 123EM other text" 它也可以不包含以下部分出现:“某些文本123EM其他文本”

I need either "200-1234" or "123" in a named capture group. 我需要命名捕获组中的“ 200-1234”或“ 123”。

I tried this: \\b([0-9]{0,3}\\-{0,1}[0-9]{3})EM\\b 我尝试了这个: \\b([0-9]{0,3}\\-{0,1}[0-9]{3})EM\\b

It does match, but it is not a named group. 它确实匹配,但它不是命名组。

When I try to name the group like this: \\b(?<test>[0-9]{0,3}\\-{0,1}[0-9]{3})EM\\b I get an error message "Unknown look-behind group near index 34" 当我尝试将组命名为: \\b(?<test>[0-9]{0,3}\\-{0,1}[0-9]{3})EM\\b我收到错误消息“索引34附近的未知后视组”

I need this to work in the .NET RegEx class 我需要这个在.NET RegEx类中工作

Thanks! 谢谢!

resultString = Regex.Match(subjectString, @"\b(?<number>\d+(?:-\d+)?)EM\b").Groups["number"].Value;

This should do the trick. 这应该可以解决问题。 If you provide more input I could make it more robust. 如果你提供更多输入,我可以使它更强大。

Explanation: 说明:

    @"
\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
"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM