多个匹配的正则表达式.net c#
Posted
技术标签:
【中文标题】多个匹配的正则表达式.net c#【英文标题】:Regex for multiple matches .net c# 【发布时间】:2021-09-04 12:32:50 【问题描述】:我正在研究一个正则表达式:
Regex regex = new Regex(@"(?<=[keyb])(.*?)(?=[\/keyb])");
有了这个正则表达式,我可以得到标签 [keyb] 和 [/keyb] 之间的所有内容
示例:[keyb]你好朋友[/keyb]
输出:你好,伙计
如果我想获取 [keyb][/keyb] 和 [keyb2][/keyb2] 之间的所有内容怎么办?
示例:[keyb]hello buddy[/keyb] [keyb2]bye buddy[/keyb2]
输出:你好,伙计
再见朋友
【问题讨论】:
您的示例与您的正则表达式不匹配。您是在解析一些用方括号表示的特殊标签,还是 XML 样式的文档? 我刚刚编辑了它!现在它匹配了! 提示:使用捕获组和反向引用。 快乐my answer 为您工作。如果您觉得我的回答有帮助,也请点赞。 【参考方案1】:使用
\[(keyb|keyb2)]([\w\W]*?)\[/\1]
见regex proof。
解释
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
keyb 'keyb'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
keyb2 'keyb2'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
] ']'
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
[\w\W]*? any character of: word characters (a-z,
A-Z, 0-9, _), non-word characters (all
but a-z, A-Z, 0-9, _) (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \2
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
\1 what was matched by capture \1
--------------------------------------------------------
C# code:
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string pattern = @"\[(keyb|keyb2)]([\w\W]*?)\[/\1]";
string input = @" [keyb]hello budy[/keyb] [keyb2]bye buddy[/keyb2]";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
Console.WriteLine("Match found: 0", m.Groups[2].Value);
结果:
Match found: hello budy
Match found: bye buddy
【讨论】:
【参考方案2】:var pattern=@"\[keyb.*?](.+?)\[\/keyb.*?\]";
【讨论】:
以上是关于多个匹配的正则表达式.net c#的主要内容,如果未能解决你的问题,请参考以下文章