我想做这样的事情:
"String with text and $abc$ and $def$ and so on... ".gsub("$*$", "replaceText")
导致
"String with text and replaceText and replaceText and so on... "
但我不知道像*
这样的通配符是如何工作的。
答案 0 :(得分:4)
您可以将regex用于此目的
"String with text and $abc$ and $def$ and so on... ".gsub(/\$\w+\$/, "replaceText")
#=> "String with text and replaceText and replaceText and so on... "
请记住,你需要逃避$
答案 1 :(得分:1)
出于好奇:一个人是否有更多的分隔符(不仅仅是美元符号),她可能会使用back-references:
str = "String with text and $abc$ and *def* and so on... "
str.gsub(/(?<delim>[$*]).*?\k<delim>/, "replaceText")
#⇒ "String with text and replaceText and replaceText and so on... "
请注意,在[]
内,无需转义$
(*
。)
答案 2 :(得分:0)
"String with text and $abc$ and $def$ and so on... ".gsub(/\$\w+\$/, "replaceText")
中尝试\ $ \ w + \ $