RSS

Regular Expressions for String Manipulations

09 Jan

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)/

 
Leave a comment

Posted by on January 9, 2010 in Strings

 

Tags: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: