0

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.

Stefan
  • 109,145
  • 14
  • 143
  • 218
SupremeA
  • 1,519
  • 3
  • 26
  • 43
  • 1
    You should take several minutes to learn [how to format code](http://stackoverflow.com/help/formatting). It helps to make your question look more clear. – Yu Hao Jul 13 '15 at 15:22

2 Answers2

7

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.

Community
  • 1
  • 1
Nic Nilov
  • 5,056
  • 2
  • 22
  • 37
1

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.

Jesus Castello
  • 1,103
  • 11
  • 20