我想在錨標記中添加 mailto 和 http 值。我試圖構建正則運算式,但我無法同時處理這兩種情況。
ex1. -> "this is test mail <mailto:[email protected]|[email protected]> testend"
output -> "this is test mail <a href=mailto:[email protected]>[email protected]</a> testend"
ex2. -> "hello <http://google.com|google.com> hello"
output -> "hello <a href=http://google.com>google.com</a> hello"
伙計們,我們可以使用任何正則運算式、gsub 方法或任何其他方法處理這些字串嗎?
我正在嘗試gsub(/<mailto:([^|]*)[^>]*>/, '<a href=#)}')但無法完成此操作?我無法理解我們如何處理上述情況。
uj5u.com熱心網友回復:
您可以為以 開頭的捕獲組使用 2 個捕獲組<mailto:
<(mailto:[^\s@|] @[^\s@|] )\|([^\s@|] @[^\s@|>] )>
解釋
<逐字匹配(捕獲組 1mailto:逐字匹配[^\s@|] @[^\s@|]匹配電子郵件格式
)關閉第 1 組\|匹配|([^\s@|] @[^\s@|>] )捕獲組 2,匹配電子郵件格式>逐字匹配
在更換使用<a href=\1>\2</a>
正則運算式演示| 紅寶石演示
re = /<(mailto:[^\s@|] @[^\s@|] )\|([^\s@|] @[^\s@|>] )>/
str = 'this is test mail <mailto:[email protected]|[email protected]> testend'
subst = '<a href=\1>\2</a>'
puts str.gsub(re, subst)
輸出
this is test mail <a href=mailto:demomail@gmail.com>demomail@gmail.com</a> testend
對于第二個示例,您可以對 2 個捕獲組使用相同的方法:
<(https?:\/\/[^\s|] )\|([^\s>] )>
正則運算式演示
對于可以用相同的替換匹配兩種場景的模式,您可以只使用|char 作為分隔符并匹配mailto:orhttps://
<((?:mailto:|https?:\/\/)[^\s|] )\|([^\s|] )>
正則運算式演示
輸出
this is test mail <a href=mailto:demomail@gmail.com>demomail@gmail.com</a> testend
hello <a href=http://google.com>google.com</a> hello
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534559.html
標籤:ruby-on-rails正则表达式红宝石ruby-on-rails-3数据结构
