3

I am weak in regex but I am learning. Currently I have a requirement to validate name and I am not able to write a valid regex for it. A valid name would contain alphabet only or alphabet with hyphens or spaces.

Example of valid name would be

jones
jones-smiht
a loreal jones

but if the name contains digits it's an invalid name. The following regex

^[-\\sa-zA-Z]+$ works fine but only - is also considered as a valid name.

How do I modify it so that a valid name must contain letters regardless or whether it contains hyphens and spaces?

4

2 回答 2

2

我认为您正在寻找这个正则表达式:

^[a-zA-Z][-\\sa-zA-Z]*$

这将确保您的姓名始终以字母开头,而不是以连字符或空格开头。

注意:在 Java 中,您还可以使用(?i)for ignore case 并缩短您的正则表达式,如下所示:

(?i)^[a-z][-\\sa-z]*$
于 2013-07-16T04:42:38.050 回答
1

你的字面答案是^[a-zA-Z][-\sa-zA-Z]*$

有更好的答案:例如,

([a-zA-Z]+)([-\s][a-zA-Z]+)*

将允许由单个空格或破折号分隔的任意数量的单词,允许simon peyton-jones,但不允许愚蠢,如--jumbo-spaz--.

并从我试图在已删除答案上发布的回复中复制:

正则表达式是单反斜杠。但是,由于正则表达式是从 Java 中的字符串构造的,因此您需要转义反斜杠;但它是字符串的特征,而不是正则表达式的特征。所以,正则表达式是\s,但你需要用Pattern.compile("\\s")Java 编写。并非所有语言都有这种扭曲,因此将字符串规则与 Regexp 分开是很有用的。

于 2013-07-16T04:42:36.790 回答