提问人:Joon 提问时间:10/27/2011 最后编辑:SLaksJoon 更新时间:10/27/2011 访问量:1118
正则表达式中的命名捕获组
named capture group in regex
问:
我需要正则表达式方面的帮助来捕获以下字符串中的数字和连字符: “一些文字和东西 200-1234EM 一些其他的东西”
它也可以在没有被炒作的部分的情况下出现: “一些文本 123EM 其他文本”
我需要命名捕获组中的“200-1234”或“123”。
我试过这个:\b([0-9]{0,3}\-{0,1}[0-9]{3})EM\b
它确实匹配,但它不是命名组。
当我尝试像这样命名该组时:我收到一条错误消息“索引 34 附近的未知后视组”\b(?<test>[0-9]{0,3}\-{0,1}[0-9]{3})EM\b
我需要它在 .NET RegEx 类中工作
谢谢!
答:
3赞
FailedDev
10/27/2011
#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
"
评论