如何使用 Ruby 从随机选择的文本中删除 50% 的笑脸?

发布于 2025-01-18 07:52:34 字数 199 浏览 3 评论 0原文

例如:

"Hi! How :) are :) you? I'm :) fine.:)".magic()
=> "Hi! How are :) you? I'm fine.:)"
or
=> "Hi! How are :) you? I'm :) fine."
or
...

唯一的:)应支持删除或更换的笑脸。

For example:

"Hi! How :) are :) you? I'm :) fine.:)".magic()
=> "Hi! How are :) you? I'm fine.:)"
or
=> "Hi! How are :) you? I'm :) fine."
or
...

Only :) smiley should be supported for deletion or replacing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷了相思 2025-01-25 07:52:34

使用:

  • String#scan 获取所有内容笑脸
  • Array#sample 的出现次数做一个随机选择要删除的
  • String#gsub 使用块参数来迭代匹配项并选择要替换为空字符串的位置

代码:

class String
  def magic()
    len = scan(/:\)/).length
    pos_to_remove = (0 ... len).to_a.sample(len / 2)
    gsub(/:\)/).with_index { |_, i|
      if pos_to_remove.include?(i) then "" else ":)" end
    }
  end
end

Use:

  • String#scan to get all occurences of the smiley
  • Array#sample to make a random selection of which to remove
  • String#gsub with a block parameter to iterate through matches and select positions to substitute with empty string

Code:

class String
  def magic()
    len = scan(/:\)/).length
    pos_to_remove = (0 ... len).to_a.sample(len / 2)
    gsub(/:\)/).with_index { |_, i|
      if pos_to_remove.include?(i) then "" else ":)" end
    }
  end
end
北渚 2025-01-25 07:52:34

关键是同时匹配两个 :) 但只捕获组中的其中一个。

  • 正则表达式
(:\).*?):\)\s*

:\)\s*(.*?:\))
  • 替换
\1

请参阅此处的测试用例

"Hi! How :) are :) you? I'm :) fine.:)".gsub(/(:\).*?):\)\s*/, '\1')
# => Hi! How :) are you? I'm :) fine.

The key is to match two :) at the same time but only capture one of them in the group.

  • regex
(:\).*?):\)\s*

or

:\)\s*(.*?:\))
  • substitution
\1

See the test case here

"Hi! How :) are :) you? I'm :) fine.:)".gsub(/(:\).*?):\)\s*/, '\1')
# => Hi! How :) are you? I'm :) fine.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文