gpt4 book ai didi

ruby - 用正则表达式替换字符串,如果某些单词与数组匹配则替换

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:26 24 4
gpt4 key购买 nike

我有一个字符串:

str = "John: hey, what's your name?.. :haha \n Stella: :foo :xx: my name is ... stella :xx:"

我想替换列表 ary = [":haha", ":xx:", ":foo", ":bar"] 中的所有表情符号和特殊字符(空格除外)使用 (.*) 使其变成这样:

John(.*) hey(.*) what(.*)s your name(.*) Stella(.*) my name is (.*) stella (.*)

enter image description here

我试过这个:

str.gsub(Regexp.new("^#{ary.join('|')}$")) { |w| "(.*)" }.gsub( /[\W ]+/, "(.*)")
# => "John(.*)hey(.*)what(.*)s(.*)your(.*)name(.*)haha(.*)Stella(.*)my(.*)name(.*)is(.*)stella(.*)"

问题:

  • 空格还是替换

最佳答案

我曾尝试创建一种更通用的方法,但最终想出了一个三步法。由于似乎无法过滤掉多个连续的 (.*),因此我添加了第三个 gsub 的后处理:

str = "John: hey, what's your name?.. :haha \n Stella: :foo :xx: my name is ... stella :xx:"
ary = [":haha", ":xx:", ":foo", ":bar"]
print str.gsub(Regexp.new("#{ary.join('|')}")) { |w| "(.*)" }.gsub( /(?>\(\.\*\)|[^\w ]+)/, "(.*)").gsub(/\(\.\*\)(?>\s*\(\.\*\))*/,"(.*)")

sample program 的输出:

John(.*) hey(.*) what(.*)s your name(.*) Stella(.*) my name is (.*) stella (.*)

关于ruby - 用正则表达式替换字符串,如果某些单词与数组匹配则替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com