Search code examples
javascriptregexlookbehind

Difficulties with constructing this JavaScript regex


I would like to construct a regular expression that matches any letter (including accented and Greek), number, hyphens and spaces with a total allowed characters length between 3 and 50.

This is what I made:

[- a-zA-Z0-9çæœáééíóúžàèìòùäëïöüÿâêîôûãñõåøαβγδεζηθικλμνξοπρστυφχψωÇÆŒÁÉÍÓÚŽÀÈÌÒÙÄËÏÖÜŸÂÊÎÔÛÃÑÕÅØΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ]{3,50}

Now I wan't to adjust the expression so that it can't start with a hyphen or space. It will be used to validate a username.

I thought about using a negative lookbehind but these are the limitations:

  • JavaScript doesn't support a lookbehind.
  • The alternatives for a lookbehind aren't really applicable since they all depend on other JavaScript functions and I am bound to using the match function.

I hope there are any regular expression heroes here since it doesn't look simple.


Solution

  • I replaced your long character class with a-z for readability:

    [a-z][- a-z]{2,49}
    

    You could also match with your current regex and then make sure that the string does not match ^[ -] in another match.