in reply to Re: Regex pattern that fails when string contains a certain pattern
in thread Regex pattern that fails when string contains a certain pattern

Your pattern does not match the second example: aa1_bb2
  • Comment on Re^2: Regex pattern that fails when string contains a certain pattern

Replies are listed 'Best First'.
Re^3: Regex pattern that fails when string contains a certain pattern
by Corion (Patriarch) on Dec 22, 2016 at 09:42 UTC

    Since I'm not going to test my regular expressions and since you don't seem to want to provide a SSCCE, let us think about a different approach, rephrasing your problem:

    If your string contains an underscore, you want that underscore to be followed by letters and then a number.

    If your string contains no underscore, you want to accept it.

    When you lok at these two statements, it should be simple for you to encode that as two separate if statements.

    If you really want to force this into one regular expression, consider a simple alternation:

    /^([^_]+|[^_]+_[a-z]+\d[^_]*)$/

    ("Either the string contains no underscore, or it contains stuff that is no underscore, followed by an underscore, letters and a digit, and then no underscores again").

    Of course, this is all vague since you don't provide code to discuss.

      I'm willing to provide code - but I have to write it first. I tested my pattern within a regex-testing GUI.

        After you've added some more specifications, let me recommend that you don't use a single regular expression. While it is still possible to create a regular expression that matchess your description, three if statements convey your rules much better.

Re^3: Regex pattern that fails when string contains a certain pattern
by kcott (Archbishop) on Dec 22, 2016 at 18:01 UTC

    Corion wrote:

    "/_[a-z]+\d/"

    You responded:

    "Your pattern does not match the second example: aa1_bb2"
    $ perl -E '"aa1_bb2" =~ /_[a-z]+\d/ && say "Yes, it does!"' Yes, it does!

    — Ken