开发者

In Ruby, how can I remove numeric words from a phrase without splitting phrase into words and losing word delimiters?

开发者 https://www.devze.com 2023-04-07 10:27 出处:网络
I am trying to remove numeric words from a phrase. I am writing the following: phrase = \'hello 234234 word\'

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消