Reputation: 75
I need to get the text from the outside pair of brackets So from the text like this with unknown number of inside blocks:
Block1{{text1}{text2} ... {text n}}
get the result:
{text1}
and
{text2} ....{text n}
Is there an easy way how to do it? Thanks!
Upvotes: 0
Views: 140
Reputation: 1580
You can use regular expressions.
String pattern = @"(Block[0-9]+){({[^}]+})*}";
String text = @"Block1{{text1}{text2}{text3}{text4}{text5}{text6}}Block2{{text1}{text2}{text3}}";
foreach(Match match in Regex.Matches(text, pattern))
{
Console.Out.WriteLine("---------");
Console.Out.WriteLine("Match: `" + match.ToString() + "`");
foreach(Group grp in match.Groups)
{
Console.Out.WriteLine(" Group: `" + grp.Value + "`");
foreach(Capture cpt in grp.Captures)
{
Console.Out.WriteLine(" Capture: `" + cpt.Value + "`");
}
}
}
Breaking down the regular expression pattern:
Capture the literal Block
and zero or more numerical digits:
(Block[0-9]+)
Process a literal {
:
{
Capture zero or more repetitions of a literal {
, one or more of anything but }
, and then a literal }
:
({[^}]+})*
Process a literal }
:
}
Here's a .NET fiddle.
edit 2: Based on conversation in the comments, the original question was intended to be broader. I think the following answer works for the specific case originally presented, but the answer above is generic.
You can use regular expressions.
String pattern = @"{({[^}]+})({[^}]+})}";
Match match = Regex.Match(text, pattern);
Console.Out.WriteLine("---------");
Console.Out.WriteLine("Match: `" + match.ToString() + "`");
if (match.Groups.Count == 3)
{
Console.Out.WriteLine(" Group 1: ``" + match.Groups[1].Value);
Console.Out.WriteLine(" Group 2: ``" + match.Groups[2].Value);
}
To break down this expression:
Match one opening curly braces:
{
Make a group out of one opening curly brace, one or more characters that are not a closing curly brace, and one closing curly brace.
({[^}]+})
Make a group out of one opening curly brace, one or more characters that are not a closing curly brace, and one closing curly brace.
({[^}]+})
Match one closing curly brace:
}
edit: I had made a mistake that I have corrected with the first regular expression; it yielded text1
rather than {text1}
and similarly for text2
.
Upvotes: 1