2013-04-07 56 views
2

我想要做的是獲取包含通配符的用戶輸入文本(所以我需要保持這種方式),而且還要查找指定的輸入。因此,舉例來說,我在下面的工作中使用了管道|。Python:匹配包含正則表達式代碼的兩個變量的OR

我想出如何使這項工作:

dual = 'a bunch of stuff and a bunch more stuff!' 
reobj = re.compile('b(.*?)f|\s[a](.*?)u', re.IGNORECASE) 
result = reobj.findall(dual) 
for link in result: 
     print link[0] +' ' + link[1] 

返回:
unchØ
           次A B

除了

dual2 = 'a bunch of stuff and a bunch more stuff!' 
#So I want to now send in the regex codes of my own. 
userin1 = 'b(.*?)f' 
userin2 = '\s[a](.*?)u' 
reobj = re.compile(userin1, re.IGNORECASE) 
result = reobj.findall(dual2) 
for link in result: 
     print link[0] +' ' + link[1] 

將返回:
ü           ň
ü           ň

我不明白它在做什麼,如果我擺脫所有保存的鏈接[ 0]打印我得到:
u
u

然而,我可以通過在用戶輸入的正則表達式的字符串:

dual = 'a bunch of stuff and a bunch more stuff!' 
userinput = 'b(.*?)f' 
reobj = re.compile(userinput, re.IGNORECASE) 
result = reobj.findall(dual) 
print(result) 

但是當我嘗試用管道更新這兩個用戶字符串:

dual = 'a bunch of stuff and a bunch more stuff!' 
userin1 = 'b(.*?)f' 
userin2 = '\s[a](.*?)u' 
reobj = re.compile(userin1|userin2, re.IGNORECASE) 
result = reobj.findall(dual) 
print(result) 

我得到的錯誤:

reobj = re.compile TypeError:不受支持的操作數類型爲|:'str'和'str'就像我在userin1 | userin2周圍放置括號()或[]一樣。

我發現以下幾點:

Python regular expressions OR

,但不能讓它的工作; .. { - (

我想什麼做的是能夠理解如何。傳遞這些正則表達式變量,比如OR,並返回兩者的所有匹配,以及諸如AND之類的東西 - 最終它是有用的,因爲它將對文件進行操作,並讓我知道哪些文件包含特定的單詞邏輯關係OR,AND等。

感謝很多您的想法,

布賴恩

+0

您必須將管道作爲字符串使用,而不是操作員。認爲:「a | b」而不是「a」| 「B」 – TankorSmash 2013-04-07 12:33:49

回答

1

雖然我不能得到A.羅達斯答案上班,他給的。加入的想法。我編制的例子 - 雖然回報略有不同(在鏈接[0]和鏈接[1]中)所需的結果。

userin1 = '(T.*?n)' 
userin2 = '(G.*?p)' 
list_patterns = [userin1,userin2] 
swaplogic = '|' 
string = 'What is a Torsion Abelian Group (TAB)?' 
theresult = re.findall(swaplogic.join(list_patterns), string) 
print theresult 
for link in theresult: 
     print link[0]+' '+link[1]