正则表达式:介于常量和可变字符之间的字符串

时间:2019-05-18 14:11:49

标签: python regex python-3.x

我有一个字符串(全文)。它由一个部分(即内置函数的名称)和第二部分(即说明)组成。 我要提取描述。

即我想提取\rPython *function_name*()\r和此\r之间的文本部分 因此结果将是“为给定函数返回类方法”

我已经尝试过此r'(?<=\\rPython .()\\r)(.*?)(?=\\r)',但是它没有显示任何发现的结果,我也不知道为什么。

#find description
fulltext=r'\rPython classmethod()\rreturns class method for given function\r'
description_regex=re.compile( r'(?<=\\rPython .()\\r)(.*?)(?=\\r)')
description= description_regex.search(fulltext)
print(description.group())

1 个答案:

答案 0 :(得分:3)

我们可以在此处尝试使用re.findall

input = "\rPython classmethod()\rreturns class method for given function\r"
matches = re.findall(r'\rPython\s+[^()]+\(\)\r(.*)\r', input)
print(matches)

此打印:

['returns class method for given function']

如果您有可能期望多个匹配项的文本,那么使用re.findall可能很有意义。