Reputation: 454
Hello I would like to eliminate non words characters by a Regex in Ruby.
Let's say that I have:
pal1 = "a@b?a"
pal1 = /[a-z0-9]/.match(pal1)
When I put this in http://www.rubular.com/, it says that the Match result is: aba
But whe I run the code in my ruby it is not true, it gives only "a"
How can I change my Regex to achieve aba in pal1.
Thanks in advance for your time.
Upvotes: 1
Views: 89
Reputation: 70722
You can use gsub
to remove these characters.
pal1 = 'a@b?a'
pal1.gsub(/[^a-z0-9]/i, '')
# => "aba"
You can also use scan
to match these characters and join them together.
pal1 = 'a@b?a'
pal1.scan(/[a-z0-9]/i).join
# => "aba"
Upvotes: 6
Reputation: 303205
You can do either of:
pal1.gsub!( /[^a-z\d]/i, '' ) # Kill all characters that don't match
pal1 = pal1.scan(/[a-z\d]/i).join # Find all the matching characters as array
# and then join them all into one string.
Upvotes: 1