问题:句子以hi
开头(不区分大小写),并且紧随其后不是空格和字母d。
我的正则表达式:[hi|HI|hI|Hi][^ d|D][a-zA-Z ]*
但是,我不理解为什么正则表达式会接受此字符串hI dave how are you doing
。
我为此使用python re库。
尝试:我尝试了不同版本的[^ ][^d|D]
,但是这些似乎都不起作用。
最佳答案
您不能在字符类中使用alternation。字符类定义一组字符。说-“匹配班级指定的一个字符”。最简单的方法是在使用内联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)
关于python - 在模式匹配方面需要帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29635285/