Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for minimum and maximum amount of words with rule

Working on a name-surname validator. We get entries by people with more than one name. I am looking for a solution.

Old regex: /[a-zA-Z]{2,}\s[a-zA-Z]{2,}$/ (Works for 1 name – 1 surname)

I am confused with part {2,} that it counts recurrence of pattern in the word, but I want it to count the words -> {2,4} for minimum 2 and maximum 4 words that fits the rule.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This doesn’t work: /[a-zA-Z\s]{2,}\w$/

>Solution :

Matching 2-4 words, where a "word" matches 2 or more chars A-Za-z:

^[a-zA-Z]{2,}(?:\s[a-zA-Z]{2,}){1,3}$

Regex demo

Note that the current character ranges are pretty strict for names.

You might also write it matching 1+ word characters, but it would still be limited:

^\w+(?:\s+\w+){1,3}$
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading