问题:一个句子以 hi(不区分大小写)开头,后面没有紧跟空格和字母 d。
我的正则表达式:[hi|HI|hI|Hi][^ d|D][a-zA-Z ]*
但是,我不明白为什么这个字符串 hI dave how are you doing 被正则表达式接受。
我正在为此使用 python re 库。
尝试:我尝试了不同的版本[^ ][^d|D],但似乎都不起作用。
请您参考如下方法:
您不能使用 alternation在一个字符类中。字符类定义一组字符。说——“匹配类(class)指定的一个字符”。最简单的方法是实现 Negative Lookahead同时利用内联 (?i)不区分大小写的修饰符和 anchoring .
(?i)^hi(?! d).*
解释:
(?i) # set flags for this block (case-insensitive)
^ # the beginning of the string
hi # 'hi'
(?! # look ahead to see if there is not:
d # ' d'
) # end of look-ahead
.* # any character except \n (0 or more times)
