0

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.

5
  • 2
    Just a tip: Check which unicode ranges the greek (and other letters) are in. You could than replace the long character list by \uxxxx-\uyyyy. Commented Feb 15, 2011 at 22:50
  • Nice tip. Gonna check that out! Commented Feb 15, 2011 at 22:52
  • This isn't a solution, but since nobody has said it yet, I want to make sure that you aren't solely using javascript to validate the user input. You should definitely have some backend code that replicates the frontend validation. Commented Feb 15, 2011 at 22:52
  • That was the plan. Thanks for the reminder. Actually there will be three types of validation depending on the browser: JavaScript validation or HTML5 browser validation and PHP validation. Commented Feb 15, 2011 at 22:54
  • @Felix Kling - Your tip is worth gold. Imagine typing all those characters manually. Commented Feb 16, 2011 at 0:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Seems to work but there's no option to prevent the whole a-z part from being duplicated? Since it's so long it would make it a lot more difficult to maintain.
you can use new RegExp(regex) if you want to convert a string to regular expression. This will allow you to set up your pattern in a string and manipulate/duplicate however you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.