正则表达式匹配可选项,除非可选项包含特定字符串

Regular expression match optional item unless optional item contains a certain string?

本文关键字:可选项 包含特 字符串 正则表达式      更新时间:2023-09-26

[问题]

我有一个 URL 方案,我正在尝试为其创建一个正则表达式。我有一部分方案是可选的,但如果某个字符串(假设字符串Apple(在字符串中的任何位置匹配,它应该失败。

[示例]

成功的字符串:

http://example.com/en/Parent
http://example.com/en/Parent/
http://example.com/en/Parent/ArbitraryWord http://example.com/en/Parent/ArbitraryWord/anythingelse

失败的字符串:

http://example.com/en/Parent/Apple http://example.com/en/Parent/Apple/anythingelse

[我尝试过的]

我从 /'/Parent'/(?!Apple)([a-zA-Z0-9]+)/gi 开始,但这与http://example.com/en/Parent不匹配,因为正则表达式需要一个尾部斜杠和另一个字符串。然后我尝试了/'/Parent('/)?(?!Apple)([a-zA-Z0-9]+)?/gi,它确实与/Parent/ URL 匹配,但在存在Apple时也不会失败。

[js小提琴]

http://jsfiddle.net/Luf9zsw4/1/

尝试以下操作:

/'/Parent(?:'/((?!Apple).*))?$/img