2013-08-30 18 views
1

假設我有記憶(基本字符串1 - String100)字符串列表如何匹配多個字符串,其中一個是'不包含'?

String1 
String2 
... 
String11 
String12 
... 
String20 
String21 
... 

什麼是一種方法,使用正則表達式,可以執行以下操作?

「匹配不包含‘字符串1’,但不包含‘String10’或‘STRING3’的所有字符串」

+0

似乎沒有串在你的列表中應該匹配,因爲沒有字符串包含'string10'和'string3' ... –

+0

我希望它匹配如果字符串不包含String1,但包含String10或String3。對不起,我會用「Or」編輯原文。 – mariocatch

+0

那麼,這實際上是語言特定的;如果是這樣,C#或Python? –

回答

2

您可以使用lookahead assertions此:

^(?=.*String(?:10|3)\b)(?!.*String1\b) 

這將匹配如果字符串包含任何String10String3,但只有當它不包含String1(假定這些單詞以某種方式被分隔,例如通過空格或其他非字母數字字符)。

比賽本身將是零長度,所以你只需要檢查是否有匹配:

>>> strings = ["String10 String1 String5", "String4", "String10 String2", 
...   "String1 String3", "String4 String3"] 
>>> regex = re.compile(r"^(?=.*String(?:10|3)\b)(?!.*String1\b)") 
>>> [string for string in strings if regex.search(string)] 
['String10 String2', 'String4 String3'] 

說明:

regex = re.compile(r""" 
     ^  # Match the start of the string 
     (?=  # Assert that the following can be matched here: 
     .*  # Any string, followed by 
     String # the word "String" and 
     (?:10|3) # either the number 10 or 3. 
     \b  # Make sure the word ends here (don't match "String100"!) 
     )   # End of lookahead. We're still at the start of the string! 
     (?!  # Assert that the following can't be matched here 
     .*  # Any string, followed by 
     String1 # "String1" 
     \b  # Make sure the word ends here (don't match "String10"!) 
     )   # End of lookahead 
     """, re.VERBOSE)  
+0

我很確定這是我需要的。我正在測試它。如果你不介意的話,你能否一張一張地分解它(比你已經做得更多)?我真的很想理解這一點,但先行文檔還不完全清楚。 – mariocatch

1

無需使用正則表達式這一點。 在Python中你可以使用這樣的事情:

>>> string1 = 'bla' 
>>> string2 = 'ble' 
>>> string3 = 'blue' 
>>> 
>>> the_string = 'blabla' 
>>> string1 in the_string and string2 not in the_string and string3 not in the_string 
True 
+0

我必須使用正則表達式,這是一個項目需求,因爲我上面的示例非常簡單,實際的實現更復雜。 – mariocatch

相關問題