我正在尝试创建一个应该匹配以下情况的正则表达式。
如果单词 'first, secondary,third'
完全匹配,则匹配应该失败 - 但如果它周围有任何字符,则应该匹配字符串。
此外,我需要避免字符串中的某些字符集。 [()!=<>", ] - 如果这些字符是字符串的一部分,则匹配结果应该失败。
我看了一些例子和负面展望,但还没有得到正确的正则表达式。
^(?!first$|second$|third$|fou rth$)[^()!=<>", ]+
期望的输出:
first - fail
second - fail
1first - pass
first1 - pass
1first1 - pass
fou rth - fail - it has space in between word and is from ignore list
newTest - pass
new(test - fail - since ( is not allowed character
space word - fail - since space is non allowed character
正则表达式需要支持不区分大小写的单词
任何帮助表示赞赏。我正在使用 JavaScript。
最佳答案
试试这个正则表达式:
^(?!.*[()!=<>", ])(?!(?:first|second|third)$).+$
说明:
-
^
- 断言字符串的开头 -
(?!.*[()!=<>", ])
- 负向前瞻以验证测试字符串不包含任何这些字符 -(
,)
,!
,=
,<
,>
,,
, -
(?!(?:first|second|third)$)
- 此时我们处于测试字符串的开头。此位置不应紧跟(first
或second
或third
),然后是字符串末尾($
) -
.+
- 匹配任何字符出现 1 次以上,但不匹配换行符 -
$
- 断言字符串结尾
关于javascript - 正则表达式 - 避免表达式中出现字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236712/