简体   繁体   中英

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.

 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.

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 . , 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, . , + , ' or -
  • (?:\\s[a-zA-Z.+'-]+)* - zero or more sequences of:
    • \\s - a single whitespace
    • [a-zA-Z.+'-]+ - 1 or more letters, . , + , ' 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 - everything except whitespace
  • "+"- 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)}`)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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