Regex: Possible combine list operator [a-z] with " "{2, } in one expression? Just letters a-z and not more than one whitespace consecutivly
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 l开发者_开发知识库ist operators? Or is there another approach.
You could simply replace all sequences of non-alphanumeric characters by a single space:
string.gsub(/[^a-zA-Z0-9]+/, " ")
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 "
精彩评论