2013-06-01 71 views
-1

我在python中這樣做,我有一個像這樣的變量。正則表達式,帶可選部分IN變量

team = "St. John's" 
db_team = "St. John's" 
db_team = "St John's" 
#I am not sure which variable db_team will equal 

re.search(team, db_team) 

,但顯然,這並不因爲球隊變量裏面時期的工作,但在同一時間,我不能隨便拿出從球隊變量的所有時段。不知道如何採取團隊變量和匹配任何db_team變量?

+1

你的總體目標是什麼?你正在使用正則表達式,它允許可選的字符串匹配 –

+0

反地球,抱歉,我不明白你的問題 – appleLover

+0

http://www.regular-expressions.info/optional.html –

回答

0
team = "St\\.? John's" 

\\是爲了躲避.?是使其可選。

2

使用re.escape來逃避你的點和所有其他陰涼的東西。

re.search(re.escape(team), db_team) 
0
import re 
team = "St. John's" 
db_team1 = "St. John's" 
db_team2 = "St John's" 

# find an exact match for 'St' without a dot, replace it with 'St.' 

db_team1 = re.sub(r'\bc\b', 'St.', db_team1) 
db_team2 = re.sub(r'\bSt(?!\.)\b', 'St.', db_team2) 
team = re.sub(r'\bSt(?!\.)\b', 'St.', team) 

# then compare strings without regex 

if team == db_team1: print "match1" 
if team == db_team2: print "match2" 

使用標準表示的方法相同的方法可以擴展到包括其它縮寫。從這個意義上講,你可以考慮先將數據庫和用戶的所有字符串轉換爲小寫字母。

相關問題