Python-在lookbehind中使用字符排除和量词来忽略字符(如果它们存在)

时间:2016-08-17 18:44:36

标签: python regex

希望能够使用能够获取值的正则表达式来获取字符串,无论后端是否存在某些内容。 例如。

下面的两个字符串
    string_1 = "this('isastring', 'secondstring')"
    string_2 = "this(\\'issomeotherstring\\', \\'ADiffSecondString\\')

我想要做的是抓住第二个字符串上的引号内的内容,无论它们是否具有双反斜杠。我尝试使用带有字符排除和量词的lookbehind但是得到一个错误,其中lookbehind必须是零宽度。对不起,对于正则表达式来说很新。

1 个答案:

答案 0 :(得分:0)

如果通过“抓取”,您的意思是找到所有字符串,您可以按照以下步骤操作:

string_1 = "this('isastring', 'secondstring')"
string_2 = "this(\\'issomeotherstring\\', \\'ADiffSecondString\\')"

import re

findall_str = re.compile(r"\\?'(.*?)\\?'").findall

print(findall_str(string_1))
print(findall_str(string_2))

你会得到:

['isastring', 'secondstring']
['issomeotherstring', 'ADiffSecondString']