我需要一个正则表达式的帮助来捕获以下字符串中的数字和连字符: “一些文字和东西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类中工作
谢谢!
答案 0 :(得分:3)
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
"