1

I'm relative new to RegEx and I've encountered a problem. I want to regex a name. I want it to be max 100 characters, contain at least 2 alphabetic characters and it will allow the character '-'.

I have no problem to only check for alphabetic characters or both alphabetic characters and hyphen but I dont't want a name that potantially can be '---------'.

My code without check for hyphens is

var nameRegExp = /^([a-z]){2,100}$/;

An explanation for the code is appreciated as well. Thanks!

3
  • So the string should contain at least one letter, or what exactly is the condition? Commented Apr 7, 2013 at 17:34
  • at least 2 letters and it can contain the character '-' but at the same time at least 2 letters Commented Apr 7, 2013 at 17:35
  • Oh yeah, sorry, I missed the 2 ;) Commented Apr 7, 2013 at 17:39

2 Answers 2

2

I guess

/^(?=.*[a-z].*[a-z])[a-z-]{1,100}$/

the lookahead part (^(?=.*[a-z].*[a-z])) checks if there are at least two letters. This pattern ("start of string, followed by...") is a common way to express additional conditions in regexes.

You can limit the number of - by adding a negative assertion, as @Mike pointed out:

/^(?=.*[a-z].*[a-z])(?!(?:.*-){11,})[a-z-]{1,100}$/  // max 10 dashes

however it might be easier to write an expression that would match "good" strings instead of trying to forbid "bad" ones. For example, this

/^[a-z]+(-[a-z]+)*$/

looks like a good approximation for a "name". It allows foo and foo-bar-baz, but not the stuff like ---- or foo----bar----.

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

2 Comments

Thanks! Is it possible to add rules to set maximum '-' characters or would it be a lot more complex?
The last code-snippet is exactly the one I'm looking for. Thanks a lot!
2

To limit the number of - you could add a negative look-ahead, where the number 3 is one more than the maximum number you want to allow

/^(?!(?:[a-z]*-){3,})(?=-*[a-z]-*[a-z])[a-z-]{2,100}$/

Comments

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.