Home > Blockchain >  add mailto and http tag in ancher tag
add mailto and http tag in ancher tag

Time:11-12

I want to add the mailto and http value in the anchor tag. I tried to build regex but i'm not able to handle these two case at a time.

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"

Guys, is there any any we can handle these string using any regex,gsub method or any other method?

i'm trying gsub(/<mailto:([^|]*)[^>]*>/, '<a href=#)}') but couldn't able to complete this? I'm not able to understand how can we handle above cases.

CodePudding user response:

You could use 2 capture groups for the one that starts with <mailto:

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

Explanation

  • < Match literally
  • ( Capture group 1
    • mailto: Match literally
    • [^\s@|] @[^\s@|] Match an email like format
  • ) Close group 1
  • \| Match |
  • ([^\s@|] @[^\s@|>] ) Capture group 2, match an email like format
  • > Match literally

In the replacement use <a href=\1>\2</a>

Regex demo | Ruby demo

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)

Output

this is test mail <a href=mailto:[email protected]>[email protected]</a> testend

For the second example, you can use the same approach with 2 capture groups:

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

Regex demo

  • Related