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

What's wrong with matching how you described it?

/_[a-z]+\d/

You haven't shown us what you tried. If you provide a small, self-contained example, that makes it much easier for us to try out the examples against your data.

  • Comment on Re: Regex pattern that fails when string contains a certain pattern
  • Download Code

Replies are listed 'Best First'.
Re^2: Regex pattern that fails when string contains a certain pattern
by hoppfrosch (Scribe) on Dec 22, 2016 at 09:34 UTC
    Your pattern does not match the second example: aa1_bb2

      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.

      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