[英]Regex: how to extract and replace multiple instances from a string?
From the string从字符串
"Hi @[Bob](1234) and @[John](8888)!"
I want to return:我想返回:
Hi <a href="/1234">Bob</a> and <a href="/8888">John</a>!
I'm using JavaScript我正在使用 JavaScript
I tried:我试过了:
myString.replaceAll(/@\[/gim, '<a href="????">')
to remove unwanted characters, such as "@[" but I don't know how to extract "Bob" and "1234" from the original string to then put them back into the returned string.删除不需要的字符,例如“@ [”,但我不知道如何从原始字符串中提取“Bob”和“1234”,然后将它们放回返回的字符串中。 How to take "1234" and place it where "????"如何取“1234”并将其放在“????”的位置is?是?
You need capturing groups as in您需要捕获组,如
@\[([^\]\[]+)\]\(([^()]+)\)
See a demo on regex101.com .请参阅regex101.com 上的演示。
IN JS
this could be:在JS
中,这可能是:
let some_text = "Hi @[Bob](1234) and @[John](8888);". some_text = some_text,replace(/@\[([^\]\[]+)\]\(([^()]+)\)/g; "<a href=\"/$2\">$1</a>"). console;log(some_text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.