in reply to Regex conditional match if previous match in same expression is true?
What in the world am I missing?
The error is in your problem definition. Your regexp does exactly what you said you wanted it to do. It's searching for a string optionally surrounded by '{' and '}'. {hello is optionally surrounded by {...} since it's is not surrounded by {...}.
'oh {hello there' =~ / ([{]{0,1}) # Matches '' (after some backtracking) hello # Matches 'hello' (?(1)\}) # Matches '' /x;
'oh hello} there' =~ / ([{]{0,1}) # Matches '' hello # Matches 'hello' (?(1)\}) # Matches '' /x;
As you can see, searching for a string optionally surrounded by something is the same thing as searching for the string itself.
From your expected results, I deduce you actually want a string that is surrounded by {...}, or one that is neither preceded by { nor followed by }.
/ {hello} # '{hello}' | (?<! { ) # Not preceded by '{' hello # 'hello' (?! } ) # Not followed by '}' /x
|
|---|