I want to validate a name for instance. A name must be composed of words separated by " " or "-". Example: "Jean-Luc Melenchon", "Xavi Hernandez"
3 Answers
If I got your requirements correctly, you want a name validator whose rule is to make sure each name contains atleast one space or one hyphen (-). You could use this regex:
^.*(\s|-)+.*$
(\s|-)+
means there should be atleast one space (\s
) or hyphen (-
).*
allows any number of characters before and after the space
Will match successfully with
Jean-Luc Melenchon
Xavi Hernandez
Lionel Messi
Zlatan Ibrahimovic
Will not match with below (because they don't have a space or a hyphen)
Deco
Rivaldo
Kaka
O'Shea

- 4,861
- 1
- 17
- 29
If this is for a lab exercise, knock yourself out. If it's going to be used in a real-life application, do not think you know what a valid name is.
Take a look at Using RegEx for validating First and Last names in Java and PHP Regex for human names
As Pascal Martin says in the latter,
one day or another, your code will meet a name that it thinks is "wrong"... And how do you think one would react when an application tells him "your name is not valid" ?

- 1
- 1

- 1,619
- 15
- 24
I tried this and it seems to be working fine
[A-Za-zàâéêèìôùûçÀÂÉÊÈÌÔÙÛÇ']+(\\s|\\-[A-Z]+)*

- 70
- 1
- 9
-
Really? How Does it treat this name? `Breandán Dalton` Or this one? Влади́мир Ильи́ч Улья́нов – Breandán Dalton May 08 '17 at 08:29