How can I match a pattern like
\\gr{\_.*:}
but so that the brackets have to match?
That is,
\gr{this should match:}
,
\gr{this should {not:} match}
\gr{nor} should {this:}
.
-
2Give two examples one to be matched and one nto be matched. Give an example text and what you wanted to match. It will help to get better answers.– SibiCoderCommented Jun 4, 2016 at 16:43
-
3If I understand your question you're asking to make sure that beginning and ending parentheses are matching parentheses. This is not possible with regular expressions. Here's a question on that that goes more into detail.– Tumbler41Commented Jun 4, 2016 at 20:59
1 Answer
Based on what you said shouldn't match (:}
is the significant delimiter), it should be as simple as:
\\gr{\_[^{]\{-}:}
However, if something like \gr{}:}
is valid since the first }
isn't preceded by a colon:
\\gr{\%(\%({\_[^}]\{-}}\)\@!\_.\)\{-}:}
\%(\%({\_[^}]*}\)\@!\_.\)
is a negative match for anything wrapped in braces. Even if the braces were nested, it should be enough to stop matching once encountered.
This pattern can be used if the braces can be escaped with a backslash:
\\gr{\%(\%(\\\@<!{\_[^}]\{-}\\\@<!}\)\@!\_.\)\{-}:}
It would be able to match:
\gr{this \{should} match:} \gr{this \{should\} match:}
\gr{this {should\} match:} \gr{this {should:} not match:}
But, this one poses a problem because it can bleed into the next line:
\gr{both lines are}
\gr{a \{single\} match:}
This is because of \\\@<!}
in the pattern, though I'm not sure why. If there isn't a need for these to span multiple lines, this pattern should be able to ignore escaped braces:
\\gr{\%(\%(\\\@<!{[^}]\{-}\\\@<!}\)\@!.\)\{-}:}
It should be noted that these patterns uses the non-greedy \{-}
repetition. If *
is used, the match would span consecutive lines which is something you wouldn't want if you wish to operate on each \gr{...:}
group individually.