正则表达式 - 避免表达式中的字符串 [英] Regular Expression - Avoid a string in expression
问题描述
我正在尝试创建一个应该符合以下情况的正则表达式。
如果完全匹配单词'first,second,third'
那么匹配应该失败 - 但是如果它周围有任何字符,那么字符串应该匹配。
I am trying to create a regex that should match following cases.
if exact match of words 'first, second, third'
then match should fail - but if there are any characters around it, then the string should be matched.
此外,我还需要避免字符串中的某些字符集。 [()!=<>,] - 如果这些字符是字符串的一部分,那么匹配结果应该失败。
Also I need to avoid certain set of characters in the string. [()!=<>", ] - if these characters are part of string then match result should fail.
我看了几个例子&负面向前看但是还没有得到正确的正则表达式。
I looked at few examples & negative look ahead but did not get the right regex yet.
^(?!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
正则表达式需要支持不区分大小写的单词
The regex needs to support case insensitive words
任何帮助表示赞赏。我使用的是javascript。
Any help appreciated. I am using javascript.
推荐答案
试试这个正则表达式:
^(?!。* [()!=<>,])(?!(?:first | second | third )$)。+ $
说明:
-
^
- 断言字符串的开头 -
(?!。* [()!=<>,])
- 用于验证测试字符串不包含任何这些字符的否定预测 -(
,)
,!
,=
,<
,>
,,
, -
(?!(?:first | second | third)$)
- 此时我们处于测试字符串的开头。此位置不应紧跟(第一个
或第二个
或第三个$ c) $ c>)然后在字符串的末尾(
$
) -
。+
- 匹配任何字符的1 +次出现,但不匹配换行符 -
$
- 断言字符串的结尾
^
- asserts the start of the string(?!.*[()!=<>", ])
- negative lookahead to validate that the test string does not contain any of these characters -(
,)
,!
,=
,<
,>
,,
,(?!(?:first|second|third)$)
- At this moment we are at the beginning of the test string. This position should not be immediately followed by (first
orsecond
orthird
) and then by the end of the string($
).+
- matches 1+ occurrences of any character but not a newline character$
- asserts the end of the string
这篇关于正则表达式 - 避免表达式中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!