tags:

views:

208

answers:

5

How to write a regular expression with the following criteria?

without

  • Numbers
  • Special Characters
  • Space
+1  A: 

In Perl, it would be something like:

$string !~ /[\d \W]/

Of course, it depends on your definition of "special characters". \W matches all non-word characters. A word character is any alphanumeric character plus the space character.

Thomas Owens
Since you're only looking for a single character, you could simply do: `$string !~ /\d|[ ]|\W/` which could be simplified as: `$string !~ /[\d \W]/`
Bart Kiers
Good call on that one. I'll edit.
Thomas Owens
A: 

You could just check regexlib.com.

slugster
A: 

The most important thing to learn about regular expressions is not their syntax, but the ability to clearly explain what you are looking for. That's really 90% of the problem.
Also, it's usually better to state what you want rather than what you don't want.

kemp
A: 

Try ^[^0-9\p{P} ]$

Paul McLean
Note that I interpreted "special characters" as puncuation. Not sure if that is what you want or not...
Paul McLean
I guess you'll want to remove `a-zA-Z` from it since you're negating it.
Bart Kiers
+4  A: 

The caret inside of a character class [^ ] is the negation operator common to most regular expression implementations (Perl, .NET, Ruby, Javascript, etc). So I'd do it like this:

[^\W\s\d]
  • ^ - Matches anything NOT in the character class
  • \W - matches non-word characters (a word character would be defined as a-z, A-Z, 0-9, and underscore).
  • \s - matches whitespace (space, tab, carriage return, line feed)
  • \d - matches 0-9

Or you can take another approach by simply including only what you want:

[A-Za-z]

The main difference here is that the first one will include underscores. That, and it demonstrates a way of writing the expression in the same terms that you're thinking. But if you reverse you're thinking to include characters instead of excluding them, then that can sometimes result in an easier to read regular expression.

It's not completely clear to me which special characters you don't want. But I wrote out both solutions just in case one works better for you than the other.

Steve Wortham
Note that the class `\s` not only matches white spaces, but all *white space characters* (line breaks and tabs as well). You (Steve) probably know this, but my comment might be beneficial to the OP.
Bart Kiers
Thanks Bart -- yes, I forgot to mention that.
Steve Wortham
No problem. Nice on-line regex tool you created b.t.w.!
Bart Kiers
Thanks man. I'm glad you like it. ;)
Steve Wortham