如何使用gsub搜索和替换regex?

时间:2022-06-09 09:05:29

I want to filter tags out of a description string, and want to make them into anchor tags. I am not able to return the value of the tag.

我想要从描述字符串中过滤标签,并想让它们成为锚定标签。我不能返回标记的值。

My input is:

我的输入:

a = "this is a sample #tag and the string is having a #second tag too"

My output should be:

我的输出应该是:

a = "this is a sample <a href="/tags/tag">#tag</a> and the string is having a <a href="/tags/second">#second</a> tag too"

So far I am able to do some minor stuff but I am not able to achive the final output. This pattern:

到目前为止,我能做一些小事情,但是我不能完成最终的输出。这种模式:

a.gsub(/#\S+/i, "<a href='/tags/\0'>\0</a>")

returns:

返回:

"this is a sample <a href='/tags/\u0000'>\u0000</a> and the string is having a <a href='/tags/\u0000'>\u0000</a> tag too"

What do I need to do differently?

我需要做什么不同的事情?

3 个解决方案

#1


5  

You can do it like this:

你可以这样做:

a.gsub(/#(\S+)/, '<a href="/tags/\1">\0</a>')

The reason why your replacement doesn't work is that you must use double escape when you are between double quotes:

替换无效的原因是在双引号之间必须使用双转义:

a.gsub(/#(\S+)/, "<a href='/tags/\\1'>\\0</a>")

Note that the /i modifier is not needed here.

注意这里不需要/i修饰符。

#2


3  

You need to give gsub a block if you want to do something with the match from the regex:

如果您想对来自regex的匹配做些什么,您需要给gsub一个块:

a.gsub(/#(\S+)/i) { "<a href='/tags/#{$1}'>##{$1}</a>" }

$1 is a global variable that Ruby automatically fills with the first capture block in the matched string.

$1是一个全局变量,Ruby在匹配的字符串中自动填充第一个捕获块。

#3


1  

Try this:

试试这个:

a.gsub(/(?<a>#\w+)/, '<a href="/tags/\k<a>">\k<a></a>')

#1


5  

You can do it like this:

你可以这样做:

a.gsub(/#(\S+)/, '<a href="/tags/\1">\0</a>')

The reason why your replacement doesn't work is that you must use double escape when you are between double quotes:

替换无效的原因是在双引号之间必须使用双转义:

a.gsub(/#(\S+)/, "<a href='/tags/\\1'>\\0</a>")

Note that the /i modifier is not needed here.

注意这里不需要/i修饰符。

#2


3  

You need to give gsub a block if you want to do something with the match from the regex:

如果您想对来自regex的匹配做些什么,您需要给gsub一个块:

a.gsub(/#(\S+)/i) { "<a href='/tags/#{$1}'>##{$1}</a>" }

$1 is a global variable that Ruby automatically fills with the first capture block in the matched string.

$1是一个全局变量,Ruby在匹配的字符串中自动填充第一个捕获块。

#3


1  

Try this:

试试这个:

a.gsub(/(?<a>#\w+)/, '<a href="/tags/\k<a>">\k<a></a>')