tags:

views:

62

answers:

2

I'm searching for a regular expression that let me replace all chars but letters and digits and one whitespace consecutively.

For example:

string = "a b c         e f g 1 2 3 !"

should be replaced in ruby to "a b c e f g 1 2 3 "

matching letters and digits is not that problem with [a-zA-Z0-9] with the list operator. but how to combine the interval operator for " "{2,} with the list operator, since intervals seem they can't be used in list operators? Or is there another approach.

+3  A: 

You could simply replace all sequences of non-alphanumeric characters by a single space:

string.gsub(/[^a-zA-Z0-9]+/, " ")
Gumbo
@Gumbo, and the uppercase as well. Then I can upvote you (since you provided the _actual_ code) ... That's better, +1.
paxdiablo
Ah, thanks a lot. So simple. But one question left when i don't replace it with one white space. which regex would i need to use? Is there a possibility to integrate interval in list?
Ndi
A: 
irb(main):001:0> string = "abc         e f g 1 2 3 !"
=> "abc         e f g 1 2 3 !"
irb(main):002:0> string.gsub(/[^[:alnum:]]/,"").gsub(/(.)/,'\1 ')
=> "a b c e f g 1 2 3 "

irb(main):002:0> string = "abc         e f g 1 2 3 !"
=> "abc         e f g 1 2 3 !"
irb(main):003:0> string.gsub(/[^a-zA-Z0-9]+/, " ")
=> "abc e f g 1 2 3 "
hi, i don't understand what does the replace exüression of the second gsub?
Ndi
the 2nd gsub means to capture every single character and replace by itself plus a space. Note that the accepted answer will not work when you have string like the one i showed.
thanks for the explanation. i thnk my first post was not distinct. the words like abc shouldn't filled up with spaces, but was my fault the example i took wasn't adequate.
Ndi