tags:

views:

43

answers:

2

HI

how can i ensure that a string contains no digits using regex in ruby?

thanks

+6  A: 

\D is the character class meaning "not digit", so you could do

^\D*$

^ forces it to start at the beginning of the line, $ forces it to continue to the end of the line.

orangeoctopus
+1 I forgot `\D` and took the longer route with `[^0-9]`.
Amarghosh
I had to look up a reference to see if \D existed, I had an inkling it did! To be honest, I think [^0-9] is more readable.
orangeoctopus
As a general rule, if there is a matcher for it, I go with that, because if there is some other language where the English character maps to some other Unicode character, then the matchers should understand and be able to handle that. I don't know if language uses other characters for digits, but if they do, \d and \D will be correct for them too, where [0-9] and [^0-9] will not.
Joshua Cheek
Good point, Joshua.
orangeoctopus
A: 

You can scan for any digit, then use !~ to match when if it cannot find one.

'1234'          !~ /\d/  # => false
'12.34'         !~ /\d/  # => false
'abc1def'       !~ /\d/  # => false
'a1b2c3d'       !~ /\d/  # => false
'12abc'         !~ /\d/  # => false
'abc12'         !~ /\d/  # => false
'oi9'           !~ /\d/  # => false
'abc'           !~ /\d/  # => true
'ABC'           !~ /\d/  # => true
'aBcD'          !~ /\d/  # => true
''              !~ /\d/  # => true
'日本語'         !~ /\d/  # => true
'~!@#%^&*()}'   !~ /\d/  # => true
Joshua Cheek