Ruby 如何为类似字符串创建正则表达式

Ruby 如何为类似字符串创建正则表达式,ruby,regex,Ruby,Regex,我有这根绳子 [url=test.php]test[/url] 或 我想用正则表达式得到这个 [url=http://test.php]text[/url] 例如: 之前: str = "[url=test.php]text[/url]" str.gsub(/\[url=(.*?)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]') => "[url=http://test.php]text[/url]" 问题: str = "[url=http:

我有这根绳子

[url=test.php]test[/url]

我想用正则表达式得到这个

[url=http://test.php]text[/url]
例如:

之前:

str = "[url=test.php]text[/url]"
str.gsub(/\[url=(.*?)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')
=> "[url=http://test.php]text[/url]"
问题:

str = "[url=http://test.php]text[/url]"
str.gsub(/\[url=(.*?)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')
=> "[url=http://http://test.php]text[/url]"
所以。。两个“http://”

有什么想法吗


谢谢你澄清了你的问题

如果链接的url不是以
http
开头,则需要一个只匹配
[url]
BBCode标记的正则表达式

\[url=\s*(?!http)([^\]]+)\](.*?)\[/url\]
应:

str.gsub(/\[url=\s*(?!http)([^\]]+)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')
说明:

\[url=\s*   # match [url= literally, plus optional space
(?!http)    # assert that it's not possible to match http here
([^\]]+)    # match 1 or more characters except ], capture in \1
\]          # match ]
(.*?)       # match link text, capture in \2
\[/url\]    # match [/url]

谢谢你澄清你的问题

如果链接的url不是以
http
开头,则需要一个只匹配
[url]
BBCode标记的正则表达式

\[url=\s*(?!http)([^\]]+)\](.*?)\[/url\]
应:

str.gsub(/\[url=\s*(?!http)([^\]]+)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')
说明:

\[url=\s*   # match [url= literally, plus optional space
(?!http)    # assert that it's not possible to match http here
([^\]]+)    # match 1 or more characters except ], capture in \1
\]          # match ]
(.*?)       # match link text, capture in \2
\[/url\]    # match [/url]