Newbie regular expression question

Hello champs,

I am having an string and i want all extra characters to be removed from
that string except + and .
How to write a regular expression for it… Currently i am trying it like
this as word.sub(/[_-:\/]/, “”)… But its not working…

I can do it like this as well:- word.sub(/[\W]/, “”) but this will
replace all characters even also + and .

Give sample input string and output string…

Le 07/04/2010 11:44, Hemant B. a écrit :

Hello champs,

I am having an string and i want all extra characters to be removed from
that string except + and .
How to write a regular expression for it… Currently i am trying it like
this as word.sub(/[_-:\/]/, “”)… But its not working…

I can do it like this as well:- word.sub(/[\W]/, “”) but this will
replace all characters even also + and .

This seems to be what you need :

str = “ABCD EF + (GH_IJ).klm _ ^^z”
str.gsub(/[^\w+.]|_/i, ‘’)
=> “ABCDEF+GHIJ.klmz”


Aurélien AMILIN

On 7 April 2010 10:44, Hemant B. [email protected] wrote:

I am having an string and i want all extra characters to be removed from
that string except + and .

word.gsub(/[^+.]/, “”)

Siddick E. wrote:

Give sample input string and output string…

Hey thanks for such a quick reply…

Ok lets suppose,
Input:- :[email protected]
Output should be as only, [email protected]

Means that i want to remove all extra chars except . and +… Hope u got
it now…

The question or the example isn’t clear enough.

But for the example you gave, this works = a.sub(/[\s_]/,’’)

Thanks & Regards,
Dhruva S…

On 7 April 2010 10:58, Michael P. [email protected] wrote:

On 7 April 2010 10:44, Hemant B. [email protected] wrote:

I am having an string and i want all extra characters to be removed from
that string except + and .

word.gsub(/[^+.]/, “”)

oh… if you want to keep alphanumeric characters:

word.gsub(/[^a-zA-Z0-9+.]/, “”)

AMILIN Aurélien wrote:

Le 07/04/2010 11:44, Hemant B. a �crit :

Hello champs,

I am having an string and i want all extra characters to be removed from
that string except + and .
How to write a regular expression for it… Currently i am trying it like
this as word.sub(/[_-:\/]/, “”)… But its not working…

I can do it like this as well:- word.sub(/[\W]/, “”) but this will
replace all characters even also + and .

This seems to be what you need :

str = “ABCD EF + (GH_IJ).klm _ ^^z”
str.gsub(/[^\w+.]|_/i, ‘’)
=> “ABCDEF+GHIJ.klmz”


Aur�lien AMILIN

Thanks guyz, this worked like a charm… Thanks to all of you who replies
so quickly …

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs