从正则表达式中排除子模式

excluding subpattern from regular expression

我有一个 JS 应用程序在我输入 "Democratic Republic of the Congo" 时触发 "Republic of the Congo"。如何告诉我的 /republic\s*of\s*the\s*congo/i 正则表达式在包含字符串 "democratic" 时不触发?

\b 不起作用,因为 "democratic" 被白色 space 分隔。

将正则表达式的边界添加为

/^republic\s*of\s*the\s*congo$/i 
  • ^ 将正则表达式锚定在字符串的开头。

  • $ 将正则表达式锚定在字符串的末尾

这些锚点确保 Republic of the Congo 之前或之后没有任何内容。


现在如果你的正则表达式支持负向后视,你也可以写成

/(?<!democratic)\s*republic\s*of\s*the\s*congo/i 
  • (?<!democratic) 断言 Republic of the Congo 前面没有 democratic