in reply to Regex conditional match if previous match in same expression is true?

Looks to me like $1 is always going to be defined. It just may be empty. Maybe what you want is (\{)? to match the open brace, very much like the example in perlre.
  • Comment on Re: Regex conditional match if previous match in same expression is true?
  • Download Code

Replies are listed 'Best First'.
Re^2: Regex conditional match if previous match in same expression is true?
by radiantmatrix (Parson) on Apr 09, 2007 at 18:04 UTC

    Well, that's certainly an improvement -- I had forgotten about all of the behaviors of the ? modifier. However, I must still be missing something. My code now reads:

    use strict; use warnings; for ( 'oh {hello} there', 'oh {hello there', 'oh hello there', 'oh hello} there', ) { print '', ( $_ =~ / (\{)? # optional opening brace hello # .. followed by 'hello' (?(1)\}) # a closing brace iif the open brace was the +re /x ? 'YEP ' : 'NOPE' ), " - $1\n"; }

    But my output is:

    YEP  - {
    YEP  - 
    YEP  - 
    YEP  - 

    However, now warnings are thrown for using an uninitialized '$1' in the last three cases, as it should be.

    What I'm struggling with is how to say that '{hello}' is OK, and 'hello' is OK, but '{hello' and 'hello}' are NOT OK. Or, put another way, I want to require a closing brace if an opening brace is found; however, if there is no opening brace then there must be no closing brace either.

    Thanks for the help, though, it's an improvement.

    <radiant.matrix>
    Ramblings and references
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet