I apologize for the confusing title, I'm in new regex territory (for me) here. I've been working my way through the excellent Mastering Regular Expressions, but I must be missing something.
I'm attempting to solve a problem wherein I'm finding a particular string in text: this string is optionally surrounded by '{' and '}'. In other words, the closing brace needs to be matched if and only if the opening brace was there.
I simplified the issue to a very minimal case in order to construct the regex, but I am getting unexpected results. Perhaps a more savvy monk than I can enlighten me as to where I've gone wrong.
use strict; use warnings; for ( 'oh {hello} there', 'oh {hello there', 'oh hello there', 'oh hello} there', ) { print '', ( $_ =~ / ([{]{0,1}) # optional opening brace hello # .. followed by 'hello' (?(1)\}) # a closing brace iif the open brace was the +re /x ? 'YEP ' : 'NOPE' ), " - $1\n"; }
This program outputs the following lines:
YEP - {
NOPE -
NOPE -
YEP -
Expected / desired results are:
YEP - {
NOPE -
YEP -
NOPE -
What in the world am I missing?
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |