gpt4 book ai didi

python - 在模式匹配方面需要帮助

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:33 26 4
gpt4 key购买 nike

问题:一个句子以 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)

关于python - 在模式匹配方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com