简体   繁体   English

正则表达式-至少一个字母数字字符并允许空格

[英]Regex - At least one alphanumeric character and allow spaces

I want to make sure a first name field has at least one alphanumeric character and also allow spaces and dashes. 我想确保名字字段至少包含一个字母数字字符,并且还允许使用空格和破折号。

**VALID**

David
Billie Joe
Han-So

**INVALID**
-

Empty is also invalid

use this pattern 使用这种模式

^(?=.*[a-zA-Z])[a-zA-Z -]+$  

Demo 演示版

oh, for alphanumeric use 哦,用于字母数字

^(?=.*[a-zA-Z0-9])[a-zA-Z 0-9-]+$ 

To ensure the dashes and spaces happen in legitimate places, use this: 为确保破折号和空格出现在合法的地方,请使用以下命令:

(?i)^[a-z]+(?:[ -]?[a-z]+)*$

See demo . 参见演示

  • (?i) puts us in case-insensitive mode (?i)使我们进入不区分大小写的模式
  • ^ ensures we're at the beginning of the string ^确保我们在字符串的开头
  • [az]+ matches one or more letters [az]+匹配一个或多个字母
  • [ -]?[az]+ matches an optional single space or dash followed by letters... [ -]?[az]+匹配可选的单个空格或破折号,后跟字母...
  • (?:[ -]?[az]+)* and this is allowed zero or more times (?:[ -]?[az]+)*并且允许零次或多次
  • $ asserts that we have reached the end of the string $断言我们已经到达字符串的末尾

You mentioned alphanumeric , so in case you also want to allow digits: 您提到了alphanumeric ,因此万一您还希望允许数字:

(?i)^[a-z0-9]+(?:[ -]?[a-z0-9]+)*$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM