crispychicken
crispychicken

Reputation: 2662

Ruby/Rails: How do I allow whitespace, dash and ÄÖÜ in my regex?

Currently my regular Expression looks like this: /\A[a-zA-Z]{2,50}\z/i

Now I would like to add acceptance of: -, whitespace and ÄÖÜ.

I tried rubular.com but I'm a total regex noob.

Upvotes: 0

Views: 411

Answers (3)

stema
stema

Reputation: 93026

Probably you want to think about using Unicode properties and scripts. You could write your regex then as

\A[\p{L}\s-]{2,50}\z

See it here on Rubular

\p{L} is a Unicode property and matching any letter in any language.

If you want to match ÄÖÜ you maybe also want ß, using Unicode properties you don't have to think about such things.

If you want to limit the possible letters a bit you can use a Unicode script such as Latin

\A[\p{Latin}\s-]{2,50}\z

See it on Rubular

Upvotes: 4

James Hibbard
James Hibbard

Reputation: 17775

In a regex, whitespace is represented by the shorthand character class \s.
A hyphen/minus is a special character, so must be escaped by a backslash \-
Ä, Ö and Ü are normal characters, so you can just add them as they are.

/\A[a-zA-Z\s\-ÄÖÜ]{2,50}\z/i

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

Just add it in the regex as follows:

/\A[a-zA-Z\-\sÄÖÜ]{2,50}\z/i

DEMO

regex is an invaluable cross-language tool that the sooner you learn, the better off you will be. I suggest putting in the time to learn it

Upvotes: 3

Related Questions