In implementing a small script parser I've come across a problem with this sample of code - in wanting to select only the part between and including the "if { }" statements, it's being greedy and selecting all including the last line. I guess what I should be using is a negative lookahead.
if [condition1]
{
task1
setparameters{a}
task2
}
if [condition2]
{
task3
}
setparameters{b}
Currently, I have:
if\b\s\[.*\]\s\{(\s|.)*\}
I guess it's not as simple as breaking on another 'if' either, as something else may come before then. Is it possible to count an equal number of opening and closing braces? Or is there some other magical way that I can just select one of these 'if' statements?
I ran into a similar problem when I was trying to detect SQL strings (with the possibility of escaped quotes), try the regex: if.*?\{(\{.*?\}|[^}])*+\}
It will match an if
followed by the condition
up until the first {
, then from then on it will continue matching if it encounters either something between a {
and }
OR anything that is not a }
, followed by the final closing }
.
I used the possessive quantifier to prevent the possibility of catastrophic backtracking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With