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?
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
Matching a Single Character Using Regex By default, the '. ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.
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,
a-z
and A-Z
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 a-z
.Note that this class won't match international characters e.g. ä. You have to include them separately e.g.
^[-'a-zA-ZÀ-ÖØ-öø-ſ]+$
A compact version for the UTF-8 world that will match international letters and numbers.
/^[\p{L}\p{N}*-]+$/u
Explanation:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With