2014-01-13 94 views
0

下面的代碼「的正則表達式的意外的結束」給我一個錯誤:「正則表達式的意外的結束」的Python:在搜索文本

import re 
my_text = "[abc" 
if re.search(my_text, "a"): 
    print "found!" 

這是因爲在my_text單括號中。這工作得很好:

my_text = "[abc]" 

首先,我不明白爲什麼一個支架應在所有問題。不匹配的括號不在正則表達式中,而在正在搜索的字符串中。

我能逃脫支架:

my_text = "\[abc" 

但是否有其他解決辦法?我寧願不要弄亂字符串的長度,因爲我也做類似my_text的東西[some_index:]

+0

開放括號在正則表達式中有特殊含義。如果它沒有匹配的右括號,則正則表達式無效。 – kindall

回答

7

re.search函數接受模式作爲第一個參數,實際字符串接受第二個參數。函數簽名如下

re.search(pattern, string, flags=0) 

所以,只是改變參數的順序。

import re 
my_text = "[abc" 
if re.search("a", my_text): 
    print "found!" 

但檢查中另一個字符串字符串存在的最簡單的方法是使用in操作,這樣

print "fourth" in "thefourtheye" # True 

從註釋部分報價docs

When s is a string or Unicode string object the in and not in operations act like a substring test. In Python versions before 2.3, x had to be a string of length 1. In Python 2.3 and beyond, x may be a string of any length.

+0

Doh!謝謝!我在代碼中至少使用了re.search至少25次,似乎突然間隔了一段距離。 (我需要使用正則表達式,因爲它實際上是在搜索「[a-zA-Z]」) – user984003

+0

@ user984003不客氣:) – thefourtheye

3

看起來你認爲re.search的第二個參數是正則表達式模式。

不,第一個參數是模式,第二個參數是字符串。

以下是re.search函數的簽名:

re.search(pattern, string, flags=0) 

BTW,你不需要使用正則表達式來檢查字符串包容。使用in運算符。

>>> "a" in "[abc" 
True 
>>> "d" in "[abc" 
False 
+0

@thefourtheye,謝謝你的糾正。 :) – falsetru