regex 在ancher标记中添加mailto和http标记

ldioqlga  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(122)

我想在锚标记中添加mailto和http值。我试图构建regex,但我无法同时处理这两种情况。

ex1. -> "this is test mail <mailto:demomail@gmail.com|demomail@gmail.com> testend"
output -> "this is test mail <a href=mailto:demomail@gmail.com>demomail@gmail.com</a> testend"

ex2. -> "hello <http://google.com|google.com> hello"
output -> "hello <a href=http://google.com>google.com</a> hello"

伙计们,有没有任何我们可以处理这些字符串使用任何regex,gsub方法或任何其他方法?
我正在尝试gsub(/<mailto:([^|]*)[^>]*>/, '<a href=#)}'),但无法完成这个?我不明白我们如何处理上述情况。

brqmpdu1

brqmpdu11#

对于以<mailto:开头的捕获组,可以使用2个捕获组

<(mailto:[^\s@|]+@[^\s@|]+)\|([^\s@|]+@[^\s@|>]+)>

说明

  • <逐字匹配
  • (捕获组1
  • mailto:逐字匹配
  • [^\s@|]+@[^\s@|]+匹配电子邮件之类的格式
  • )关闭组1
  • \|匹配|
  • ([^\s@|]+@[^\s@|>]+)捕获组2,匹配电子邮件之类的格式
  • >逐字匹配

在替换中使用<a href=\1>\2</a>
Regex demo|Ruby demo

re = /<(mailto:[^\s@|]+@[^\s@|]+)\|([^\s@|]+@[^\s@|>]+)>/
str = 'this is test mail <mailto:demomail@gmail.com|demomail@gmail.com> 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>]+)>

Regex demo
对于可以使用相同替换匹配两个场景的模式,可以只使用|字符作为分隔符,并匹配mailto:https://

<((?:mailto:|https?:\/\/)[^\s|]+)\|([^\s|]+)>

Regex demo
输出量

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

相关问题