[英]Regex for multiple matches .net c#
我正在研究正则表达式:
Regex regex = new Regex(@"(?<=[keyb])(.*?)(?=[\/keyb])");
有了这个正则表达式,我得到了标签 [keyb] 和 [/keyb] 之间的所有内容
示例:[keyb]你好伙伴[/keyb]
output:你好伙计
如果我想获得 [keyb][/keyb] 和 [keyb2][/keyb2] 之间的所有内容怎么办?
示例:[keyb]你好伙伴[/keyb] [keyb2]再见伙伴[/keyb2]
output:你好伙计
再见哥们
采用
\[(keyb|keyb2)]([\w\W]*?)\[/\1]
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
( 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
--------------------------------------------------------
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
var pattern=@"\[keyb.*?](.+?)\[\/keyb.*?\]";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.