使用 OR `|` 时否定正则表达式

Negate a RegEx when using OR `|`

我有一个 RegEx 模式

^(\d+|\w+-\d+)$

如何匹配所有那些不匹配此模式的字符串?

如果您研究它并尝试理解它。从逻辑上讲它会是这样的。假设如果有一个条件说 XY 那么它的否定既不是 X 也不是 Y.

X or Y negation 将等于 Neither X and Nor Y.

为此你可以试试这个。

Regex code demo

正则表达式: ^(?!\d+$)(?!\w+-\d+$).*$

1. ^ start of string.

2. (?!\d+$) negative look-ahead for digits till the end of string.

3. (?!\w+-\d+$) negative look-ahead for words then - and then digits till the end.

4. .*$ match all till then end.