python - 用于在 Python 中查找括号的正则表达式

标签 python regex

我正在尝试查找大写字母后跟括号的所有匹配项,即 A)、B)、C) 等。我通过重试对其进行了测试 (http://re-try.appspot.com/) 并且它工作得很好,但是当我在我的程序中实现它时,它给了我一条错误消息:sre_constants.error: unbalanced parenthesis

parens = re.findall(r'[A-Z]\)', test_file)

好像忽略了转义符,这是为什么呢? 任何帮助或替代方法将不胜感激。

最佳答案

这个有效:

>>> st='first A) you have B) and then C)'
>>> re.findall(r'[A-Z]\)',st)
['A)', 'B)', 'C)']

或:

>>> re.findall('[A-Z]\\)',st)
['A)', 'B)', 'C)']

test_file 实际上是一个字符串吗?你所拥有的应该可以工作(在 Python shell 中尝试)所以我怀疑你的第二个参数是 re.findall...

如果正如您的命名所暗示的那样,它是一个文件对象,您需要这样做:

with open('file.txt','r') as f:
    for line in f:
        line_matches=re.findall(pattern,line)
        ... do something with a list of matches from that line
        ... next line

或者,对于整个文件

with open('file.txt', 'r') as f:
    contents=f.read()
    file_matches=re.findall(pattern,contents,flags=re.MULTILINE)
    ... do something with a list of matches from the whole file

或者,那个文件的编码可能是错误的...

关于python - 用于在 Python 中查找括号的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14028023/

相关文章:

java - 正则表达式在每个句点后分割一个段落,但在缩写后不分割

c# - 在 C# 中使用正则表达式删除字符

python - 向 k 均值添加特征

python - 如何按列获取重复数字的长度?

python - 使用python获取样本中wav文件的长度

捕获两个常量之间的任何文本的正则表达式

python - 选择 ML 的最佳功能

python - 使用 libcloud 为 gce 实例创建 sshKey

使用 OR 运算符的 Python 正则表达式

C# 正则表达式