C# 使用正则表达式仅匹配第n个匹配项

C# 使用正则表达式仅匹配第n个匹配项,c#,regex,C#,Regex,我有一个字符串,其中包含3个日期,如下所示: XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx 我想选择字符串中的第二个日期,即201802081 在regex中是否有这样的方法,我们必须在代码中退出2个匹配项。如果有必要的话,我正在使用C 谢谢您的帮助。您可以使用 ^(?:[^_]+_){2}(\d+) 以第一组为例,参见。 这个说,坏了 ^ # start of the string (?:[^_]+_

我有一个字符串,其中包含3个日期,如下所示:

XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx
我想选择字符串中的第二个日期,即
20180208
1

regex
中是否有这样的方法,我们必须在代码中退出2个匹配项。如果有必要的话,我正在使用
C

谢谢您的帮助。

您可以使用

^(?:[^_]+_){2}(\d+)
以第一组为例,参见。
这个说,坏了

^              # start of the string
(?:[^_]+_){2}  # not _ + _, twice
(\d+)          # capture digits
:

你可以用

请参见下面的示例

Regex regex = new Regex(@"^(?:[^_]+_){2}(\d+)"); //Expression from Jan's answer just showing how to use C# to achieve your goal
GroupCollection groups = regex.Match("XXXXX_20160207_20180208_XXXXXXX_20190408T160742_xxxxx").Groups;
if (groups.Count > 1)
{
    Console.WriteLine(groups[1].Value);
}
试试这个

MatchCollection matches=Regex.matches(sInputLine,@“\d{8}”)

字符串sSecond=匹配[1]。ToString()


可以使用正则表达式

^(?:.*?\d{8}_){1}.*?(\d{8})
保存第二个日期以捕获组1

当然,对于
n>2
,将
{1}
替换为
{n-1}
,以获得第n个日期。要获取第一个日期,请使用

C#的正则表达式引擎执行以下操作

^        # match the beginning of a line
(?:      # begin a non-capture group
  .*?    # match 0+ chars lazily
  \d{8}  # match 8 digits
  _      # match '_'
)        # end non-capture group
{n}      # execute non-capture group n (n >= 0) times
.*?      # match 0+ chars lazily     
(\d{8})  # match 8 digits in capture group 1
需要注意的重要一点是,
*?
的第一个实例后面紧跟着
\d{8}
,因为它是惰性的,所以它会尽可能多地吸收字符,直到下一个8个字符是数字(并且前面或后面没有数字。例如,在字符串中)

_1234abcd_efghi_123456789_12345678_ABC

(.*?)中的捕获组1将包含
“\u 1234abcd\u efghi\u 123456789”
最好的方法是在
上拆分并抓取
x
出现。但是,仅在正则表达式中执行此操作,您可以使用
(?
^([^]*]){3}
并捕获第一组也可以,因为只捕获了组的最后一个匹配项。这并不是说它更好。@Aaron:请随意将其作为备选答案发布,因为它也可以。Meh,最好在regex101中使用您的IMO,13步对19步。它更像是展示regex功能。您的regex给出的结果不正确如果字符串以第一个日期开始,或者如果日期在字符串中的位置不同..复制我的表达式并在一小时后将其作为答案?对不起,我的意思不是复制你的exp,而是演示如何使用c代码来使用它
^        # match the beginning of a line
(?:      # begin a non-capture group
  .*?    # match 0+ chars lazily
  \d{8}  # match 8 digits
  _      # match '_'
)        # end non-capture group
{n}      # execute non-capture group n (n >= 0) times
.*?      # match 0+ chars lazily     
(\d{8})  # match 8 digits in capture group 1
_1234abcd_efghi_123456789_12345678_ABC