假设有一系列字符串。重要项目用引号括起来,但其他项目用转义引号括起来。你怎么能只返回重要的物品?
返回两者的示例:
import re
testString = 'this, is a test "one" it should only return the first item \"two\" and not the second'
pattern = = '"([^\\\"]*)"'
print re.findall( pattern, testString)
打印结果
['one', 'two']
我如何让python只能打印
['one']
答案 0 :(得分:3)
您可以使用negative lookbehinds确保报价前没有反斜杠:
import re
testString = r'this, is a test "one" it should only return the first item \"two\" and not the second'
pattern = r'(?<!\\)"([^"]*)(?<!\\)"'
# ^^^^^^^ ^^^^^^^
print re.findall(pattern, testString)
答案 1 :(得分:0)
这里即使您使用\“标记其他项目,但在python中它只被解释为”两个“。您可以使用python原始字符串,其中\”将被视为\“
import re
testString = r'this, is a test "one" it should only return the first item \"two\" and not the second'
pattern = '"(\w*)"'
print re.findall( pattern, testString)