Regular expression to match a name
javascript, regex
Solution
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À-ÖØ-öø-ſ]+$
Problem
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?