簡體   English   中英

有沒有辦法讓 Regex.Match 只提供預期的捕獲組?

[英]Is there a way to have Regex.Match provide only the intended capture group?

c# regex.match 似乎工作的方式是返回的唯一捕獲組值包括與模式匹配的整個字符串。 相反,我只想要 1 美元。 現在我必須執行第二步過程來清理結果。 有沒有更干凈的方法可以將其減少到 1 步?

var lineText = @"Reservations 03Mar19";
var m1Pattern = @"^\s*Reservations.*\b(\d{2}\w{3}\d{2})$";

Match m1 = Regex.Match(lineText, m1Pattern);
if (m1.Success) MyDate = Regex.Replace(m1.Groups[0].Captures[0].Value, m1Pattern, @"$1");

您可以使用?:在您的組中告訴正則表達式不要捕獲該組:

(?:this group is not captured(but this one is))

比較這個演示這個演示

這是C# 演示

使用MyDate = m1.Groups[1].Value應該MyDate = m1.Groups[1].Value您的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM