我正在尝试查找大写字母后跟括号的所有匹配项,即 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/