0

I am trying to construct a regex statement that matches a string conforming to the following conditions:

  1. 3-63 lowercase alphanumeric characters, plus "." and "-"
  2. May not start or end with . or -
  3. Dashes and periods cannot be adjacent to each other.

abc-123.xyz <- should match

abc123-.xyz <- should not match

I have been able to put this regex together, but it does not catch the third requirement. I've tried to use another negative lookahead/lookbehind,[i.e. - (?!.-|-.) ] but its still matching the strings with adjacent periods and dashes. Here's the regex statement I came up with that fulfills conditions 1 & 2:

^(?!\.|-)([a-z0-9]|\.|-){3,63}(?<!\.|-)$

FYI, this regex is for validating input when specifiying an AWS S3 bucket name in a CloudFormation template.

3 Answers3

0

How about:

^(?=.{3,63}$)[a-z0-9]+(?:[-.][a-z0-9]+)*$
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    [`^(?=.{3,63}$)[a-z0-9]+(?:[-.]?[a-z0-9]+)*$` is a bad pattern](https://regex101.com/r/QNk8IB/1). See [here why](https://stackoverflow.com/questions/45463148/fixing-catastrophic-backtracking-in-regular-expression/45477009#45477009). – Wiktor Stribiżew Aug 03 '17 at 14:32
  • 1
    @WiktorStribiżew: Thanks for info. – Toto Aug 03 '17 at 14:34
0

Use this Pattern ^(?!.*[.-](?=[.-]))[^.-][a-z0-9.-]{1,61}[^.-]$ Demo

#    ^(?!.*[.-](?=[.-]))[^.-][a-z0-9.-]{1,61}[^.-]$
^               # Start of string/line
(?!             # Negative Look-Ahead
  .             # Any character except line break
  *             # (zero or more)(greedy)
  [.-]          # Character in [.-] Character Class
  (?=           # Look-Ahead
    [.-]        # Character in [.-] Character Class
  )             # End of Look-Ahead
)               # End of Negative Look-Ahead
[^.-]           # Character not in [.-] Character Class
[a-z0-9.-]      # Character in [a-z0-9.-] Character Class
{1,61}          # (repeated {1,61} times)
[^.-]           # Character not in [.-] Character Class
$                # End of string/line
alpha bravo
  • 7,838
  • 1
  • 19
  • 23
-1
^[a-z0-9](?:[a-z0-9]|[.\-](?=[a-z0-9])){2,62}$

We match a lowercase alphanumeric character, followed by between 2 and 62 repetitions of either:

  • a lowercase alphanumeric character, or
  • a . or - (which must be followed by a lowercase alphanumeric character).

The last restriction makes sure that you can't have two ./- characters in a row, or a ./- at the end of the string.

melpomene
  • 84,125
  • 8
  • 85
  • 148