通过gsub
的以下用法,我希望"No, but I heard it's short and soft."
放在blockquotes之间。第一次,它是空的。当我立即再次运行时,它就做对了。
clean_content = "[quote="PDrizzle":1g581fap]No, but I heard it's short and soft.[/quote:1g581fap]\r\n\r\nwith very few ascents\r\n\r\nheh"
clean_content.gsub(
/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/,
"<blockquote>#{$1}</blockquote>"
)
# => "<blockquote></blockquote>\r\n\r\nwith very few ascents\r\n\r\nheh"
clean_content.gsub(
/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/,
"<blockquote>#{$1}</blockquote>"
)
# => "<blockquote>No, but I heard it's short and soft.</blockquote>\r\n\r\nwith very few ascents\r\n\r\nheh"
任何想法发生了什么?
答案 0 :(得分:4)
gsub
期望替换字符串中的反向引用格式为\\1
而不是$1
。在您的示例中,第一次发生的字符串替换是指空字符串的变量,第二次是通过执行第一次模式匹配来设置的。
所以你想要:
clean_content.gsub(/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, "<blockquote>\\1</blockquote>")
答案 1 :(得分:0)
请记住,对参数的评估先于评估采用它们的方法。首先,您有$1
= ""
,因此gsub
的第一个实例相当于
gsub(
/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/,
"<blockquote></blockquote>"
)
使得$1
= "No, but I heard it's short and soft."
,因此您的第二个gsub
实例等同于
gsub(
/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/,
"<blockquote>No, but I heard it's short and soft.</blockquote>"
)
当你第三次这样做时,你将再次拥有
gsub(
/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/,
"<blockquote></blockquote>"
)