Search code examples
regexpcre

String must be alphanumeric and contain a certain substring


I'm working on adding a regex that determines whether a given input is valid. The input should be alpha numeric (underscores, dashes, periods also allowed) and between 1 and 60 characters. It should also contain a certain substring inside it (let's just say "foo.bar"). This is my attempt:

^.[a-zA-Z0-9_.-]{1,60}$

That does what I need, aside from the substring part. I'm not sure how to add the "the string must contain the substring foo.bar" requirement. FWIW I'm doing this in Ruby so I understand this means PCRE is being used.

As an example, this string should be valid:

aGreatStringWithfoo.barInIt1111

this shouldn't

aBadStringWithoutTheSubstringInIt

Solution

  • Use

    ^(?=.{1,60}$)[a-zA-Z0-9_.-]*foo\.bar[a-zA-Z0-9_.-]*$
    

    See regex proof.

    EXPLANATION

    --------------------------------------------------------------------------------
      ^                        the beginning of the string
    --------------------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    --------------------------------------------------------------------------------
        .{1,60}                  any character except \n (between 1 and
                                 60 times (matching the most amount
                                 possible))
    --------------------------------------------------------------------------------
        $                        before an optional \n, and the end of
                                 the string
    --------------------------------------------------------------------------------
      )                        end of look-ahead
    --------------------------------------------------------------------------------
      [a-zA-Z0-9_.-]*          any character of: 'a' to 'z', 'A' to 'Z',
                               '0' to '9', '_', '.', '-' (0 or more times
                               (matching the most amount possible))
    --------------------------------------------------------------------------------
      foo                      'foo'
    --------------------------------------------------------------------------------
      \.                       '.'
    --------------------------------------------------------------------------------
      bar                      'bar'
    --------------------------------------------------------------------------------
      [a-zA-Z0-9_.-]*          any character of: 'a' to 'z', 'A' to 'Z',
                               '0' to '9', '_', '.', '-' (0 or more times
                               (matching the most amount possible))
    --------------------------------------------------------------------------------
      $                        before an optional \n, and the end of the
                               string