2015-03-24 42 views
2

假設有一系列字符串。重要的項目包含在引號中,但其他項目包含在轉義引號中。你怎麼能只返回重要的項目?在Python中使用re查找引號中的項目,但未使用引號,

例子,其中兩個被返回:

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']

回答

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) 

regex101 demo

ideone demo

+0

謝謝!這正是我需要的! – kaerus 2015-03-24 21:15:45

+0

@kaerus不客氣:) – Jerry 2015-03-24 21:15:58

0

在這裏,即使你使用\「來標記其他項目,但在Python它被解釋爲‘會被視爲兩個’裏\ only.You可以使用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) 
相關問題