1

HI

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

thanks

2 Answers 2

7

\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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.