python - python 中的正则表达式与 grep 的功能不匹配

标签 python regex python-2.7 osx-yosemite

我有以下字符串:

string1; 1.8w/v PEG_8000; string2; ;;

我想获取; 1.8w/v PEG_8000; 部分。我尝试了以下方法:

a =re.search(';[^.;]+PEG[^.;]+;','string1; 1.8w/v PEG_8000; string2; ;;'

返回 a = None

我错过了什么?

(OS X 优胜美地,Python 2.7)

编辑:我之前说过以下内容,但我发现这不是真的。我忘了我在尝试之前编辑了字符串。

The funny thing is, if I do grep -E --color ';[^.;]+PEG[^.;]+;' file, where file contains the string, it can highlight it.

编辑 2: 我有一个包含此类字符串的巨大文件,其中关键字 PEG 不一定出现在第二个字段中。这就是我不使用 split(';') 的原因。

最佳答案

一个否定的字符类匹配所有除了那些指定的字符。因此,文字 . 导致了这里的问题。您可以按如下方式修改您的正则表达式:

>>> import re
>>> s = 'string1; 1.8w/v PEG_8000; string2; ;;'
>>> re.search(';[^;]+PEG[^;]+;', s).group()
'; 1.8w/v PEG_8000;'

关于python - python 中的正则表达式与 grep 的功能不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837544/

相关文章:

python - 用 numba.jit 编译条件数组需要很长时间

mysql - 在mysql中使用正则表达式替换表中的列值

python |多处理 |分割数据

ruby * 匹配字符串

regex - 如何使用 AWK 从字符串中删除所有小写字符?

macos - 自从在Mac OS X Yosemite上安装python 3以来,ipython Notebook无法启动

Python如何缩短uuuid并解码?

python - 使用 Python 和 OpenCV 的中值滤波器

python - 在 python 中,是否有一个 setdefault() 等效于获取对象属性?

python - HTTP 错误 504 : Gateway Time-out when trying to read a reddit comments post