{
Main Block
{
Nested Block
}
}
{
Main Block
{
Nested Block
}
{
Nested Block
}
}
I want to get data within Main Blocks including its Nested Blocks with Java Regex. Is it possible?
Thanks in Advance
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
IF there can only be at most 1 level of nesting, and the braces characters can not be escaped, then in fact the regex pattern for this is quite simple.
Essentially the structure we have, in some abstract notation, is:
Here’s a visual breakdown:
This is not quite regex, of course, because:
{and}, since they’re metacharacters…with the actual pattern for content[^{}]*+would be a fine pattern. The[…]is a character class.[^…]is a negated character class. The*is zero-or-more repetition. The+following the repetition specifier is the possessive quantifier.So, meta-regexing technique is used to programmatically transform this abstract pattern (which is readable) to valid regex pattern (which can be ugly at times like this). Here’s an example (also see on ideone.com):
As you can see, the actual regex pattern is therefore:
Which as a Java string literal:
Variations
If the nesting level can be deeper, then regex can still be used. You can also allow the
{and}to be “escaped” (i.e. used in the content part but not as block delimiter).The final regex pattern will be quite complicated, but depending on how comfortable you are with meta-regexing (which requires you to be comfortable with regex itself), the code can be quite readable and manageable.
If the nesting level can be arbitrarily deep, then some flavors (e.g. .NET or Perl) can still handle it, but Java regex is not powerful enough to handle it.