在正则表达式命名的捕获组 [英] named capture group in regex

查看:475
本文介绍了在正则表达式命名的捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

它也可以出现无hypenated部分: 一些文字123EM其他文本

我需要的不是200-1234,或在一个名为捕获组123。

我尝试这样做: \ B([0-9] {0,3} \ - {0,1} [0-9] {3})EM \ b

这确实匹配,但是它不是一个命名组。

当我尝试命名该组是这样的: \ B(<试验> [0-9] {0,3} \ - {0,1} [0-9] {3})EM \ b 我得到一个错误信息未知看看隐藏组近34指数

我需要这在.NET正则表达式类的工作。

谢谢!

解决方案

  resultString = Regex.Match(subjectString,@\ B(<数量> \ D +(?:? - ?\ d +))EM \ B)组。[数量]值。
 

这应该做的伎俩。如果你提供更多的投入,我可以使其更加坚固。

说明:

  @
\ B#在单词边界断言位置
(LT;数>#匹配正EX $ P $下面pssion并捕获其匹配到的反向引用名称为数字
   \ D#匹配单个数字0..9
      +#之间的一个,不限次数,多次越好,需要回馈(贪婪)
   (?:#匹配下面的常规EX pression
       - #匹配字符 - 从字面上
      \ D#匹配单个数字0..9
         +#之间的一个,不限次数,多次越好,需要回馈(贪婪)
   )? #零至1次,多次越好,需要回馈(贪婪)
)
EM#匹配字符EM的字面
\ B#在单词边界断言位置

 

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"

It can also appear without the hypenated part: "some text 123EM other text"

I need either "200-1234" or "123" in a named capture group.

I tried this: \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"

I need this to work in the .NET RegEx class

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
"

这篇关于在正则表达式命名的捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆