Ruby、gsub 和正则表达式
快速背景:我有一个字符串,其中包含对其他页面的引用。 这些页面使用以下格式链接:“#12”。 哈希值后跟页面 ID。
假设我有以下字符串:
str = 'This string links to the pages #12 and #125'
我已经知道需要链接的页面的 ID:
page_ids = str.scan(/#(\d*)/).flatten
=> [12, 125]
如何循环遍历页面 id 并将 #12 和 #125 链接到他们各自的页面? 我遇到的问题是,如果我执行以下操作(在 Rails 中):
page_ids.each do |id|
str = str.gsub(/##{id}/, link_to("##{id}", page_path(id))
end
这对于 #12 来说效果很好,但它将 #125 的“12”部分链接到 ID 为 12 的页面。
任何帮助都会很棒。
Quick background: I have a string which contains references to other pages. The pages are linked to using the format: "#12". A hash followed by the ID of the page.
Say I have the following string:
str = 'This string links to the pages #12 and #125'
I already know the IDs of the pages that need linking:
page_ids = str.scan(/#(\d*)/).flatten
=> [12, 125]
How can I loop through the page ids and link the #12 and #125 to their respective pages? The problem I've run into is if I do the following (in rails):
page_ids.each do |id|
str = str.gsub(/##{id}/, link_to("##{id}", page_path(id))
end
This works fine for #12 but it links the "12" part of #125 to the page with ID of 12.
Any help would be awesome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你的索引总是以单词边界结束,你可以匹配:
你只需要在搜索模式上添加单词边界符号
\b
,对于替换模式来说不需要。if your indexes always end at word boundaries, you can match that:
you only need to add the word boundary symbol
\b
on the search pattern, it is not necessary for the replacement pattern.您不必先提取 id,然后替换它们,只需一次性查找并替换它们:
即使您不能省略提取步骤,因为您在其他地方也需要 id,这应该会快得多,因为它不必遍历每个 id 的整个字符串。
PS:如果
str
没有从其他地方引用,您可以使用str.gsub!
而不是str = str.gsub
Instead of extracting the ids first and then replacing them, you can simply find and replace them in one go:
Even if you can't leave out the extraction step because you need the ids somewhere else as well, this should be much faster, since it doesn't have to go through the entire string for each id.
PS: If
str
isn't referred to from anywhere else, you can usestr.gsub!
instead ofstr = str.gsub