It is many a times a basic necessity for us to validate a string for occurence of any special characters other than alphabets and for any numeric characters. In such cases the regular expressions can be used to match the string wih a pattern.
Ex: To see if a string has a special character, ( !, @, # … )
string=~/(\W)/
This returns the position of first occurence of any non-word characters in the string and returns nil if not there. Remember, numbers are not non-word characters.
“madan”=~/(\W)/ yields nil
“m@dan#”=~/(\W)/ yields 1, the position of first occurrence of a non-word character.
Similarly, for tracing any numeric character,
string=~/(\d)/ returns the position of first occurrence of digit character.
“ranjeet”=~/(\d)/ yields nil
“ran0je1et”=~/(\d)/ yields 3.
Similarly use
\D for non digit characters
\w for word characters
To check if a string has only pure numbers, just use,
if string=~/(\D)/ == nil
it is a pure numeric.
To check more than one patterns,
string=~/(\D)|(\W)/