Reputation: 1621
I am trying to make a regular expression that validates letters, numbers and spaces ONLY. I dont want any special characters accepted (i.e. # )(*&^%$@!,)
I have been trying several things but nothing has given me letters(uppercase & lowercase), numbers, and spaces.
So it should accept something like this...
John Stevens 12
james stevens
willcall12
or
12cell space
but not this
12cell space!
John@Stevens
james 12 Fall#
I have tried the following
^[a-zA-Z0-9]+$
[\w _]+
^[\w_ ]+$
but they allow special characters or dont allow spaces. This is for a ruby validation.
Upvotes: 1
Views: 8594
Reputation: 5156
You almost got it right. You could use this:
/\A[a-z0-9\s]+\Z/i
\s
matches whitespace characters including tab. You could use (space) within square brackets if you need exact match for space.
/i
at the end means match is not case sensitive.
Take a look at Rubular for testing your regexes.
EDIT: As pointed out by Jesus Castello, for some scenarios one should use \A
and \Z
instead of ^
and $
to denote string boundaries. See Difference between \A \Z and ^ $ in Ruby regular expressions for the explanation.
Upvotes: 7
Reputation: 1113
Here is a working example that will print matching results:
VALIDATION = /\A[a-zA-Z0-9 ]+\Z/
words = ["willcall12", "John Stevens 12", "12cell space!", "John@Stevens"]
words.each do |word|
m = word.match(VALIDATION)
puts m[0] if m
end
I can recommend this article if you would like to learn more about regular expressions.
Upvotes: 1