1

通过以下用途gsub,我希望"No, but I heard it's short and soft."将其放在块引号之间。第一次,它是空的。当我立即再次运行它时,它做对了。

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"

有什么想法吗?

4

2 回答 2

4

gsub期望替换字符串中的反向引用被格式化为\\1而不是$1. 在您的示例中,第一次发生的字符串替换是指一个空字符串变量,第二次是通过执行第一个模式匹配来设置的。

所以你要:

clean_content.gsub(/\[quote(?:.*)\](.*?)\[\/quote(?:.*)\]/, "<blockquote>\\1</blockquote>")
于 2012-09-26T02:36:41.587 回答
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>"
)
于 2012-09-26T03:26:23.303 回答