In Ruby, how can I remove numeric words from a phrase without splitting phrase into words and losing word delimiters?
I am trying to remove numeric words from a phrase. I am writing the following:
phrase = 'hello 234234 word'
words = phrase.split(/\W/)
words.reject!{ |w| w.match(/^\d+$/) }
words.join(' ')
or, one-liner:
phrase = phrase.split(/\W/).reject{ |w| w.match(/^\d+$/) }.join(' ')
Example:
"hello 123 word" should end "hello word"
"hello 123word" should end "hello 123word"
"hello 123.word" should end "hello word"
The开发者_StackOverflow社区 problem with this solution is that it removes the word delimiters too. (See the 3rd example above)
Is there a better, neater way to do that and save word delimiters at the same time?
This regex does the job:
phrase.gsub!(/\b\d+\b/, "")
This gsub
gets rid of the numeric words.
I would do it like this:
phrase.gsub!(/ \d+ /, " ")
The brackets are required to prevent ruby thinking that you're trying a line-continuation.
精彩评论