Jake Metz
Jake Metz

Reputation: 97

regex - Allow only one space and one hypen in a name

Currently, my regex is allowing for multiple spaces and hyphens but simply not allowing them one after another in a name.

Currently it allows for multiple spaces and hypens:

vjbn-bjnlm-bnj-

gvjhb vgbhjk vghj

vgjbh-vgh vghb vghbj-

How would I adjust this to ONLY allow for 1 of space or hypen EACH:

jhbn-vgbh vghjbj

My current regex is:

/^[À-ÿA-Za-z]+(?:[À-ÿA-Za-z]+|([-' ])(?!\1))*/

Upvotes: 0

Views: 100

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

At the beginning, you can add negative lookahead for .+-.+-, thus excluding strings with more than one dash, and then use the same sort of pattern again to exclude strings with more than one space:

^(?!.+-.+-)(?!.+ .+ )[À-ÿA-Za-z]+(?:[À-ÿA-Za-z]+|([-' ])(?!\1))*
 ^^^^^^^^^^^^^^^^^^^^

https://regex101.com/r/61kC3C/1

Upvotes: 3

Related Questions