[英]Ruby (Rails) gsub: pass the captured string into a method
我正在尝试匹配字符串:
text = "This is a #hastag"
raw(
h(text).gsub(/(?:\B#)(\w*[A-Z]+\w*)/i, embed_hashtag('\1'))
)
def embed_hashtag('data')
#... some code to turn the captured hashtag string into a link
#... return the variable that includes the final string
end
我的问题是当我在我用gsub调用的embed_hashtag方法中传递'\\1'
时,它只是简单地传递"\\1"
,而不是我的正则表达式中的第一个捕获组。 还有其他选择吗?
供参考:
我在h
包装文本以转义字符串,但后来我将代码嵌入到用户输入的文本(即主题标签)中,这些文本需要原始传递(因此是raw
)。
保持“#”符号与文本分开很重要,这就是为什么我认为我需要捕获组。
如果你有更好的方法做到这一点,请不要犹豫让我知道,但为了回答这个问题,我仍然想要一个答案,以防其他人有这个问题。
gsub(regex){ $1 }
而不是gsub(regex, '\\1')
/\\B#(\\w+)/i
h()
帮助器,Rails 4默认会逃避恶意输入 embed_hashtag(data)
而不是embed_hashtag('data')
embed_hashtag
link_to(text, url)
这应该做的伎俩:
def embed_hashtag(tag)
url = 'http://example.com'
link_to tag, url
end
raw(
text.gsub(/\B#(\w+)/i){ embed_hashtag($1) }
)
正确的方法是在这里使用一个块。
示例 :
def embed_hashtag(data)
puts "#{data}"
end
text = 'This is a #hashtag'
raw(
h(text).gsub(/\B#(\S+)/) { embed_hashtag($1) }
)
尝试最后一次匹配正则表达式快捷方式:
=> 'zzzdzz'.gsub(/d/) { puts $~[0] }
=> 'd'
=> "zzzzz"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.