[英]How do I match string patterns except for one version
我有一组字符串,我们想向用户展示。
我们要匹配所有形式为XYZ -____- xxx-tests的字符串,除非____是API。
ABCDEFGH - don't match
XYZ-api-xxx-tests - don't match
XYZ-google-xxx-tests - match
XYZ-bing-xxx-tests - match
我们现在正在使用正则表达式,但它甚至与字符串模式的“ API”版本都匹配。 如何更改我的正则表达式,使其不匹配?
尝试: XYZ-(?!api)\\w+-xxx-tests
(?!api)
是(?!api)
一词的否定前瞻。 因此,在XYZ-
之后,如果找到了api,它将停止匹配。 \\w+
表示同一位置的任何字母数字字符。 字符串的其余部分只是实际的字符匹配。
请参阅regex演示和说明: https : //regex101.com/r/Pc7lBP/1
根据您使用结果的方式,另一个常用的习惯用法是将列入黑名单的“匹配项”放在第一个替换项中,然后捕获第二个替换项。
XYZ-api-xxx-tests|(XYZ-\w+-xxx-tests)
无论如何,都应该匹配,但是如果比较的字符串是黑名单匹配,则捕获的组中将没有任何内容。 您将得到一堆结果,这些结果可以是字符串,也可以是非字符串,并且可以从那里进行过滤。
这是可行的方法:
XYZ-(?!api).*-xxx-tests
https://regex101.com/r/wWLbv4/1
负前瞻(?!api)
const regex = /XYZ-(?!api).*-xxx-tests/g; const str = `ABCDEFGH - don't match XYZ-api-xxx-tests - don't match XYZ-google-xxx-tests - match XYZ-bing-xxx-tests - match `; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.