[英]Regex & JS how to regex match a string between " and partial patterns (match first few characters and no special pattern)
我一直在努力制作这个正则表达式,很想在这里得到一些帮助。
所以我想匹配一个 url 字符串,如果它是
.dont_match1
或.dont_match1/
类的模式然后将example.com
替换为example2.com
。
例如,
bla ...... "https://example.com/content/a.dont_match1"
bla ...... "https://example.com/content/a.dont_match2"
不匹配
href="https://example.com/"
匹配并替换为 =>href="https://example2.com/"
<link rel="canonical" href="https://example.com adasd /" />
由于愚蠢的空间没有匹配
<link rel="manifest" href="https://example.com/a/asd/aaaa">
匹配并替换为 =><link rel="manifest" href="https://example2.com/a/asd/aaaa">
所有这些行都在一个文件中。
坚持了一段时间,尝试了很多,但效果不佳
(=".*)(example.com)([^\\s])*"
(=".*)(example.com)([^\\s|^.dont_match1 |^.dont_match2])*"
您可以使用
/("https:\/\/)example\.com(?![^\s"]*\.(?:dont_match1|dont_match2)\/?")([^\s"]*")/g
替换$1example2.com$2
。 请参阅正则表达式演示。
细节
("https:\\/\\/)
- 第 1 组 ( $1
): "https://
字符串example\\.com
- 一个example.com
字符串(?![^\\s"]*\\.(?:dont_match1|dont_match2)\\/?")
- 如果有零个或多个字符而不是空格和"
后跟一个.
,则匹配失败的负前瞻要么dont_match1
或dont_match2
,然后可选/
再一个"
立即到当前位置的右([^\\s"]*")
- 第 2 组 ( $2
):除空格和"
之外的零个或多个字符,然后是"
字符。JavaScript 演示:
const array = ['bla ...... "https://example.com/content/a.dont_match1"', 'bla ...... "https://example.com/content/a.dont_match2"', 'href="https://example.com/" ']; const rx = /("https:\\/\\/)example\\.com(?![^\\s"]*\\.(?:dont_match1|dont_match2)\\/?")([^\\s"]*")/g; array.forEach( x => console.log(x, '=>', x.replace(rx, '$1example2.com$2')) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.