去除正则表达式上的开始/结束字符

2024-06-25 06:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下正则表达式:

>>> re.findall(r'\r\n\d+\r\n',contents)[-1]
'\r\n1621\r\n'
>>> re.findall(r'\r\n\d+\r\n',contents)[-1].replace('\r','').replace('\n','')
'1621'

如何改进正则表达式,使其不需要使用pythonreplace方法?你知道吗

请注意,数字必须由这些字符包围,我不能直接\d+。你知道吗


Tags: 方法recontents数字字符replacefindallpythonreplace
3条回答

user 5061答案很好。
您可以使用.strip()除去那些"\r\n"特殊字符。你知道吗

re.findall(r'\r\n\d+\r\n',contents)[-1].strip()

只需使用括号:

re.findall(r'\r\n(\d+)\r\n',contents)[-1]

这样,您就可以匹配给定的模式,并且只获得findall结果中的括号内容。你知道吗

您可以使用向前看和向后看断言:

re.findall(r'(?<=\r\n)\d+(?=\r\n)',contents)[-1]

相关问题 更多 >