假设一个正则表达式应该对包含子字符串 hello
的任何字符串测试为真,后跟任何不以 !
或多个 !< 开头的字符串
.
为清楚起见,举几个例子:
var regExp = /someExpression/;
regExp.test("hello"); // → true
regExp.test("hello!"); // → false
regExp.test("hello!!"); // → false
regExp.test("hello!sdkfjhsdfjkh"); // → false
regExp.test("hellos!dkfjhsdfjkh"); // → true
regExp.test("hello-!"); // → true
regExp.test("hello w34~342`!!"); // → true
我尝试了几种方法,这是我最好的:
var regExp = /.*hello[^!].*/;
这适用于我能想到的所有情况,但只有一个:"hello"
。
在这种情况下,[^!]
需要一个字符。
我如何改进此正则表达式,使其在这种情况下也能测试正确?
感谢任何形式的帮助。
编辑 - 奖励积分:
hello
前面有一个 !
,所以 hello
被接受,但是 !hello
是不是。
最佳答案
你需要使用一个否定的前瞻而不是一个否定的字符类(仍然匹配,消耗字符):
var regExp = /.*hello(?!!).*/;
参见 regex demo
查看更多详细信息 regular-expressions.info :
Negative lookahead is indispensable if you want to match something not followed by something else. When explaining character classes, this tutorial explained why you cannot use a negated character class to match a
q
not followed by au
. Negative lookahead provides the solution:q(?!u)
. The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point.
编辑:
由于JS正则引擎不支持look-behind,所以需要匹配(^|[^!])hello
(where (^|[^!])
匹配字符串的开头或 !
以外的符号),然后使用 JS 字符串方法对它做任何你需要做的事情。
关于javascript - 正则表达式 : substring not followed by character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32852533/