python - 正则表达式匹配 [^a-z] 或 $

标签 python regex

我需要一些关于字符串正则表达式匹配句子中的单词的帮助,包括标点符号和行尾。我对行尾情况的尝试失败。

以下示例根据我的需要进行评估:

>>> print bool(re.search('test[^a-z]','test!'.lower()))
True
>>> print bool(re.search('test[^a-z]','test aaa'.lower()))
True
>>> print bool(re.search('test[^a-z]','testaaa'.lower()))
False

然而,行尾计算结果为 False:

>>> print bool(re.search('test[^a-z]','test'.lower()))
False

行尾字符 $ 不在集合 a-z 中,所以是本地的 我认为这种情况也会评估 True。我如何在 regex 中处理这个问题?

最佳答案

您可以使用负数 lookahead :

'test(?![a-z])'

或者一个 alternation :

'test([^a-z]|$)'

关于python - 正则表达式匹配 [^a-z] 或 $,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13159426/

相关文章:

python - 从文件中读取两个字符串

用于匹配 Windows 和 Posix 系统的日期时间的 C++ 正则表达式模式

html - Notepad++ RegEx 删除 2 个 html 标签之间的所有内容(中间有换行符)

python - 在正则表达式后添加一个新行

c++ - PHP-CPP C++ 扩展找不到正则表达式

python - 设置 x 轴刻度的格式

python - 用转义引号替换字符串中的所有引号?

python - Spyder Python 快捷方式选择当前行上方的所有文本

python - scrapy抓取多个页面,提取数据并保存到mysql中

php - 使用正则表达式分割管道(|)分隔的字符串,但忽略括号中的管道