Andreas
Andreas

Reputation: 2366

RegEx a name with special characters in javascript

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!

Upvotes: 1

Views: 1586

Answers (2)

georg
georg

Reputation: 214959

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----.

Upvotes: 2

MikeM
MikeM

Reputation: 13631

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}$/

Upvotes: 2

Related Questions