匹配不包含特定模式的特定字符串

时间:2020-12-24 00:29:30

标签: javascript regex

我有网址,只想匹配那些与此模式匹配的网址

^/zxp/companies/.*?/queries/.*?$

但不包含此 type=inbox - 例如 - regexp 应给出以下结果:

"/zxp/companies/432523/queries/4344?read=2&type=inbox"   -> FALSE
"/zxp/companies/432523/queries/4344?type=inbox&read=2"   -> FALSE
"/zxp/companies/432523/queries/4344?type=query&read=2"   -> TRUE
"/zxp/companies/432523/queries/4344"                     -> TRUE
"/zxp/companies/432523/buildings/4344?type=query&read=2" -> FALSE
"/zxp/companies/432523/buildings/4344"                   -> FALSE

我尝试了这个,但得到了错误的结果(仅当 type=inbox 位于字符串末尾时才有效)

let re = /^\/zxp\/companies\/.+?\/queries\/.*(?<!type=inbox)$/

let tests = [
  "/zxp/companies/432523/queries/4344?read=2&type=inbox",
  "/zxp/companies/432523/queries/4344?type=inbox&read=2",
  "/zxp/companies/432523/queries/4344?type=query&read=2",
  "/zxp/companies/432523/queries/4344",
  "/zxp/companies/432523/buildings/4344?type=query&read=2",
  "/zxp/companies/432523/buildings/4344",
]



tests.forEach(t => console.log(`${t} -> ${re.test(t)}`))

如何使用 JavaScript RegExp 来实现?

3 个答案:

答案 0 :(得分:2)

您尝试的模式使用 type=inbox 断言字符串不以 (?<!type=inbox)$ 结尾,这是一个否定的后视。

您可以改为使用否定前瞻,将其添加到 /queries/ 之后,以断言从该位置开始 type=inbox 不会出现在右侧。

注意它也会匹配 /zxp/companies/432523/queries/

^\/zxp\/companies\/.+?\/queries\/(?!.*\btype=inbox\b).*$

Regex demo

模式的一个更具体的变体可能是

^\/zxp\/companies\/\d+\/queries\/\d+\b(?!.*\btype=inbox\b).*$

Regex demo

let re = /^\/zxp\/companies\/.+?\/queries\/(?!.*type=inbox).*$/

let tests = [
  "/zxp/companies/432523/queries/4344?read=2&type=inbox",
  "/zxp/companies/432523/queries/4344?type=inbox&read=2",
  "/zxp/companies/432523/queries/4344?type=query&read=2",
  "/zxp/companies/432523/queries/4344",
  "/zxp/companies/432523/buildings/4344?type=query&read=2",
  "/zxp/companies/432523/buildings/4344",
]



tests.forEach(t => console.log(`${t} -> ${re.test(t)}`))


由于 JavaScript 中有 more support 用于使用后视,另一个选项可能是您尝试的模式的变体,断言最后一个 / 之后的部分不包含 type=inbox。

^\/zxp\/companies\/.+?\/queries\/.*(?<!\btype=inbox\b[^\r\n/]*)$

Regex demo

答案 1 :(得分:1)

你可以试试这个:

^\/zxp\/companies\/.*?\/queries\/(?!.*?type=inbox).*?$

希望对你有用。

enter image description here

我向您推荐此页面进行正则表达式测试: https://regexr.com/

enter image description here

对于这些情况,在“Flags”选项中选择并为多个匹配选择“Global”,为多行匹配“^$”选择“MultiLine”

答案 2 :(得分:0)

let checkIfType = /type=inbox/;
myString = 'checkmystringtype=inbox';
if(!checkIfType.test(myString)){
  //code here will work if there is no 'type=inbox' inside string
}
相关问题