简体   繁体   English

带正则表达式的gsub删除一个字符

[英]gsub with regular expression removes one character

I have an article model (article.rb): 我有一篇文章模型(article.rb):

class Article < ActiveRecord::Base
  attr_accessible :name, :content
end

I have a gsub like this in my article.rb: 我的文章中有一个像这样的gsub .rb:

self.content.gsub!(/anylink[^']/i, "<%= link_to 'anylink', 'http://website.com/anylink' %>")

This substitutes the word "anylink" in the text of an article with the "link_to 'anylink', 'http://website.com/anylink'" to create an automatic link. "anylink"文章文本中的"anylink"替换为"link_to 'anylink', 'http://website.com/anylink'"来创建自动链接。 When there is already a "link_to..." , it will NOT substitute since I excluded the ' after anylink in the regular expression. 当已经存在"link_to..." ,它将不会替换,因为我排除了正则表达式中的任何链接之后的'

It works, but the problem is that it deletes the next character following "anylink" . 它有效,但问题是它删除了"anylink"之后的下一个字符。 Eg it converts: 例如它转换:

"Have a look at anylink and see"

to

"Have a look at anylinkand see"

"anylink" in this second phrase now is a hyperlink, so everything is fine except the missing space that has been deleted during the gsub operation. 第二个短语中的"anylink"现在是一个超链接,所以除了在gsub操作期间删除的缺失空间外,一切都很好。 Any ideas why and how I can avoid this? 任何想法为什么以及如何避免这种情况?

String#gsub replaces the whole matching part of your pattern with your replacement, which is here the anylink string and one character which is not an apostrophe. String#gsub用你的替换替换你的模式的整个匹配部分,这里是anylink字符串一个不是撇号的字符。

So it would replace the following Strings for example: 所以它会替换以下字符串,例如:

  • anylinkA
  • anylink.
  • anylink!

If you want to keep your character, you could create a match and put that after the replacement: 如果你想保留你的角色,你可以创建一个匹配并在替换后放置:

self.content.gsub!(/anylink([^'])/i, "<%= link_to 'anylink', 'http://website.com/anylink' %>\\1")

Here the matching group ([^']) will match on the character and the escaped \\1 will put that char after your replacement. 这里匹配组([^'])将匹配字符,转义后的\\1将在替换后放置该字符。

But I recommend you to use the \\b to match the word boundary : 但我建议你使用\\b来匹配单词边界

self.content.gsub!(/\banylink\b/i, "<%= link_to 'anylink', 'http://website.com/anylink' %>")

So with this solution the word anylink will be replaced by the gsub and it can be preceded or followed any character but not an alphanumeric. 所以使用这个解决方案,anylink这个词将被gsub取代,它可以在任何字符之前或之后,但不能是字母数字。

If you want to replace all matches in self.content , add g regexp modifier: 如果要替换self.content所有匹配项,请添加g regexp修饰符:

self.content.gsub!(/\banylink\b/ig, "<%= link_to 'anylink', 'http://website.com/anylink' %>")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM