I want to write a regular expression for First name validation .
The regular expression should include all alphabets (latin/french/german characters etc.). However I want to exclude numbers from it and also allow -
.
So basically it is \w
(minus) numbers (plus) -
.
Please help.
In regex, the uppercase metacharacter denotes the inverse of the lowercase counterpart, for example, \w for word character and \W for non-word character; \d for digit and \D or non-digit.
=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol.
^[\p{L}-]+$
\p{L}
matches any kind of letter from any language.
As far as I know, Ruby doesn't support Unicode properties (at least until version 1.8), so you might need to use
^(?:[^\W\d_]|-)+$
Explanation: [^\W\d_]
matches any letter (literally it means "Match a character that is neither a non-alphanumeric character, a digit, or an underscore"). In this case, a double negative is the right thing to use. Since we're using a negated character class, we then need to allow the -
by alternation.
Caveat: From regular-expressions.info it looks like Ruby only matches ASCII characters with the \w
shorthand, so this regex might not work as intended. I don't have Ruby installed here, but on rubular.com this regex is working correctly.
The alternate solution
^[[:alpha:]-]+$
should match non-ASCII characters according to regular-expressions.info and RegexBuddy, but on rubular.com it's not working.
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