Reputation: 101
I'm workin on a regex:
Regex regex = new Regex(@"(?<=[keyb])(.*?)(?=[\/keyb])");
With this regex im gettig everything between tags [keyb] and [/keyb]
example: [keyb]hello budy[/keyb]
output: hello buddy
What about if I want to get everything between [keyb][/keyb] and also [keyb2][/keyb2] ?
example: [keyb]hello budy[/keyb] [keyb2]bye buddy[/keyb2]
output: hello buddy
bye buddy
Upvotes: 1
Views: 385
Reputation: 18641
Use
\[(keyb|keyb2)]([\w\W]*?)\[/\1]
See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
( 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);
}
}
}
Results:
Match found: hello budy
Match found: bye buddy
Upvotes: 1