简体   繁体   English

正则表达式,仅将名称与一个空格匹配

[英]regular expression to match name with only one spaces

I have a string condition in js where i have to check whether name entered in text box contains with one space only. 我在js中有一个字符串条件,我必须检查在文本框中输入的名称是否仅包含一个空格。

 pattern: name.status === 'full_name' ? /^[a-zA-Z.+-.']+\s+[a-zA-Z.+-. ']+$/ : /^[a-zA-Z.+-. ']+$/

But the above regex matches names ending with 2 spaces also. 但是上面的正则表达式也匹配以2个空格结尾的名称。

I need to match it such that the entered name should accept only one space for a name string. 我需要对其进行匹配,以使输入的名称只能接受一个空格作为名称字符串。 So the name will have only one space in between or at the end. 因此,名称之间或末尾只有一个空格。

Two observations: 1) \\s+ in your pattern matches 1 or more whitespaces, and 2) [+-.] matches 4 chars: + , , , - and . 两个观察:1) \\s+中的模式匹配1个或多个空格,以及2) [+-.]匹配4个字符: +,-. , it is thus best to put the hyphen at the end of the character class. ,因此最好将连字符放在字符类的末尾。

You may use 您可以使用

/^[a-zA-Z.+'-]+(?:\s[a-zA-Z.+'-]+)*\s?$/

See the regex demo 正则表达式演示

Details 细节

  • ^ - start of string ^ -字符串开头
  • [a-zA-Z.+'-]+ - 1 or more letters, . [a-zA-Z.+'-]+ -1个或多个字母, . , + , ' or - +'-
  • (?:\\s[a-zA-Z.+'-]+)* - zero or more sequences of: (?:\\s[a-zA-Z.+'-]+)* -零个或多个序列:
    • \\s - a single whitespace \\s单个空格
    • [a-zA-Z.+'-]+ - 1 or more letters, . [a-zA-Z.+'-]+ -1个或多个字母, . , + , ' or - chars +'-字符
  • \\s? - an optional whitespace -可选的空格
  • $ - end of string. $ -字符串结尾。

Note: if the "names" cannot contain . 注意:如果“名称”不能包含. and + , just remove these symbols from your character classes. + ,只需从字符类中删除这些符号即可。

/^\S+\s\S+$/

try this 尝试这个

Some explanations: 一些解释:

  • ^ - start of string ^-字符串开头
  • \\s - single whitespace \\ s-单个空格
  • \\S - everything except whitespace \\ S-除空格外的所有内容
  • "+"- quantifier "one or more" “ +”-量词“一个或多个”
  • $ - end of string $-字符串结尾

you could also use word boundaries... 您还可以使用单词边界...

 function isFullName(s) { return /^\\b\\w+\\b \\b\\w+\\b$/.test(s); } ['Giuseppe', 'Mandato', 'Giuseppe Mandato'] .forEach(item => console.log(`isFullName ${item} ? ${isFullName(item)}`)) 

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

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