views:

76

answers:

3

Hello ,

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.

+5  A: 
^[\p{L}-]+$

\p{L} matches any kind of letter from any language.

Amarghosh
+4  A: 

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.

Tim Pietzcker
Maybe coz its not ruby specific?
Shripad K
@Shripad K: What do you mean?
Tim Pietzcker
A: 

If you want a ruby specific solution to your validation problem then you can use this:

^[\D-]+$

You can check this permalink here:

http://rubular.com/r/VrAIB4TkwJ

I have made this a community wiki so that everyone can try it out and better the regex if required.

Hope this helps. Cheers :)

Shripad K
Tim Pietzcker