[英]question about regex
我有代碼
s = Regex.Match(item.Value, @"\/>.*?\*>", RegexOptions.IgnoreCase).Value;
它返回像'/> test *>'這樣的字符串,我可以替換符號'/>'和'*>',但是如果沒有這個符號,我如何返回字符串,它們之間只有字符串'test'?
您可以將模式分組到regx中並從匹配項中獲取
var match= Regex.Match(item.Value, @"\/>(?<groupName>.*)?\*>", RegexOptions.IgnoreCase);
var data= match.Groups["groupName"].Value
您可以通過在區域周圍放置()
來保存正則表達式的一部分。 因此,對於您的示例:
// item.Value == "/>test*>"
Match m = Regex.Match(item.Value, @"\/>(.*?)\*>");
Console.WriteLine(m.Groups[0].Value); // prints the entire match, "/>test*>"
Console.WriteLine(m.Groups[1].Value); // prints the first saved group, "test*"
我還刪除了RegexOptions.IgnoreCase
因為我們沒有專門處理任何字母,大寫/>
什么樣的? :)
您還可以使用look-ahead和look-behind 。 以您的示例為例:
var value = Regex.Match(@"(?<=\/>).*?(?=\*>)").Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.