简体   繁体   中英

Regular expression to match a name

I am trying to write a regular expression in Javascript to match a name field, where the only allowed values are letters, apostrophes and hyphens. For example, the following names should be matched:

jhon's
avat-ar
Josh

Could someone please help me construct such a regex?

Yes.

^[a-zA-Z'-]+$

Here,

  • ^ means start of the string, and $ means end of the string.
  • […] is a character class which anything inside it will be matched.
  • x+ means the pattern before it can be repeated once or more.

Inside the character class,

  • az and AZ are the lower and upper case alphabets,
  • ' is the apostrophe, and
  • - is the hyphen. The hyphen must appear at the beginning or the end to avoid confusion with the range separator as in az .

Note that this class won't match international characters eg ä. You have to include them separately eg

^[-'a-zA-ZÀ-ÖØ-öø-ſ]+$

A compact version for the UTF-8 world that will match international letters and numbers.

/^[\p{L}\p{N}*-]+$/u

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • p{N} => matches any kind of numeric character
  • *- => matches asterisk and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters.

Note, that if the hyphen is the last character in the class definition it does not need to be escaped . If the dash appears elsewhere in the class definition it needs to be escaped , as it will be seen as a range character rather then a hyphen.

更紧凑的版本是[\\w'-]+

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