Home > Software engineering >  RegEx: matching 20 letters with 1 optional dash
RegEx: matching 20 letters with 1 optional dash

Time:11-03

I'm struggling to write a regex that matches the following requirements:

  1. up to 20 characters (English letters and numbers)
  2. may have one optional dash ( - ) but can't start or end with it

I could come up with this patters: ^[a-zA-Z0-9-]{0,20}$ but this one allows for multiple dashes and one may enter the dash at the begin/end of the input string.

CodePudding user response:

You can use

^(?=.{0,20}$)(?:[a-zA-Z0-9] (?:-[a-zA-Z0-9] )?)?$

See the regex demo.

Details:

  • ^ - start of string
  • (?=.{0,20}$) - zero to twenty chars allowed in the string
  • (?: - a non-capturing group start:
    • [a-zA-Z0-9] - one or more alphanumeric chars
    • (?:-[a-zA-Z0-9] )? - an optional sequence of a - and one or more alphanumeric chars
  • )? - end of the non-capturing group, repeat one or zero times (i.e. the pattern match is optional)
  • $ - end of string.

CodePudding user response:

Have a try with:

^(?:[^\W_]{1,20}|(?!.{22})[^\W_] -[^\W_] )$

See an online demo

  • ^ - Start-line anchor;
  • (?: - Open non-capture group;
    • [^\W_]{1,20} - Match between 1-20 alphanumeric characters;
    • | - Or;
    • (?!.{22})[^\W_] -[^\W_] - Negative lookahead to assert position is not followed by 22 characters, and next we matching 1 alphanumeric characters between an hyphen;
  • )$ - Close non-capture group before matching end-line anchor.

Note that the above assumes upto 20 alphanumeric characters but with one optional hyphen that would take the max count to 21 characters.

CodePudding user response:

You can match two different regex and put both regex in OR:

First regex is to match:

  • up to 20 chars (no dash admitted)

^\w{1,20}


Second regex is to match:

  • one character at start (no dash)
  • optional up to 18 characters or dashes
  • one final character (no dash)

^\w[\w-]{1,18}\w$


Complete solution:

^\w{0,20}$|^\w[\w-]{0,18}\w$
  • Related