przbadu
przbadu

Reputation: 6049

Fetch params from url and remove any non alphabet characters and numbers?

I will be getting url in any of the following format:

- ?M=Foo bar
- ?M=Foo%20bar
- ?M=%20Foo_bar
- ?M=Foo bar?
- ?M=F00_bar
- ?M=Foo#1bar_do

OR any combination of words, special character and Numbers.

I can simply fetch value using

 params[:M]

PROBLEM :

But, now i want to convert the output and store it to variable 'm' like:

 m = FooBar

1) Here, ignore all other characters ((underscore)_, #1, space, ?, etc) and numbers and take only alphabets.

2) combine the result to form something like :

FooBar
FooBarDo

I am not good in regular expression so, I will really appreciate any help to fix this

Upvotes: 1

Views: 83

Answers (3)

mpiccolo
mpiccolo

Reputation: 672

I would highly recommend checking out http://rubular.com/ if you would like to learn more about regex. It allows you play around with regex and a string to show matches.

The other answers are good but you could use gsub as well.

"Foo#1bar_do".gsub(/\p{^Alpha}/, "") #=> "Foobardo"
"Foo%20bar".gsub(/\p{^Alpha}/, "")   #=> "Foobar"

Upvotes: 0

Vamsi Krishna
Vamsi Krishna

Reputation: 3792

Check this,

m.scan(/[a-z]+/i).join

>> m = "Foo bar"
=> "Foo bar"
>> m.scan(/[a-z]+/i).join
=> "Foobar"
>> m = "Foo%20bar"
=> "Foo%20bar"
>> m.scan(/[a-z]+/i).join
=> "Foobar"
>> m = "%20Foo_bar"
=> "%20Foo_bar"
>> m.scan(/[a-z]+/i).join
=> "Foobar"
>> m = "Foo bar?"
=> "Foo bar?"
>> m.scan(/[a-z]+/i).join
=> "Foobar"
>> m = "F00_bar"
=> "F00_bar"
>> m.scan(/[a-z]+/i).join
=> "Fbar"
>> m = "Foo#1bar_do"
=> "Foo#1bar_do"
>> m.scan(/[a-z]+/i).join
=> "Foobardo"

Upvotes: 1

Bala
Bala

Reputation: 11244

Here is one way of doing it using scan

m = "Foo%20bar"
m.scan(/[A-Za-z]/).join #=> Foobar

m = "Foo#1bar_do"
m.scan(/[A-Za-z]/).join #=> Foobardo

m = "F00_bar"
m.scan(/[A-Za-z]/).join #=> Fbar

So, in your case you would be using something similar to this:

params[:M].scan(/[A-Za-z]/).join

Upvotes: 2

Related Questions