简体   繁体   中英

Ruby- How to remove all words which have a specific pattern in a string

For example, the string is "I am very happy today". I want to remove all words containing the letter "a". So the output should be "I very". how can I do that?

Similar to @Sam's answer, only smaller :) Uses the little known Enumerable#grep_v .

Inverted version of #grep. Returns an array of every element in enum for which not Pattern === element.

"I am very happy today".split.grep_v(/a/).join(' ') # => "I very"

您可以尝试拆分每个单词并删除带有字母'a'的单词并将这些单词连接在一起,如下所示:

"I am very happy today".split.reject{ |word| word.include?("a") }.join(" ")

Here's an example with a regex :

  • word boundary
  • alphanumeric characters
  • a
  • alphanumeric characters
  • word boundary

You need to remove the unneeded spaces then.

"I am very happy today".gsub(/\b\w*a\w*\b/i, '').strip.gsub(/\s+/, ' ')

The answers with split and join are cleaner, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM