Regular expression for matching name

I am trying to write a regular expression in Javascript to match a field name, where the only valid values โ€‹โ€‹are letters, apostrophes, and hyphens. For example, the following names must be mapped:

jhon's avat-ar Josh 

Can someone help me create such a regex?

+4
source share
3 answers

Yes.

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

Here

  • ^ means start of line, and $ means end of line.
  • [โ€ฆ] is a character class that matches any inside.
  • x+ means the pattern before it can be repeated one or more times.

Inside a character class

  • az and az are lower and upper case alphabets,
  • ' is an apostrophe, and
  • - - this is a hyphen. A hyphen should appear at the beginning or end to avoid confusion with the range delimiter, as in az .

Note that this class will not match international characters, for example. รค. You must include them separately, for example.

 ^[-'a-zA-Zร€-ร–ร˜-รถรธ-ลฟ]+$ 
+8
source

A compact version for the world of UTF-8, which will correspond to international letters and numbers.

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

Explanation:

  • [] => character class definition
  • p {L} => matches any letter character from any language
  • p {N} => matches any kind of numeric character
  • * - => matches asterisk and hyphen
  • + => Quantifier - Matches between one to unlimited time (greedy)
  • / u => Unicode modifier. Template strings are treated as UTF-16. Also calls 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 a dash appears elsewhere in the class definition, it needs to be escaped , since it will be treated as a range symbol, not a hyphen.

+1
source

More compact version [\w'-]+

0
source

Source: https://habr.com/ru/post/1308140/


All Articles