2010-06-28 81 views
4

這是一個涉及Python中的條件正則表達式的問題:Python的條件正則表達式

我想​​匹配字符串

match(1)="a" 
match(2)="b" 
match(3)="c" 

而且還匹配字符串" a"

match(1)="a" 
match(2)="" 
match(3)="" 

以下代碼幾乎是這樣做的,問題是在第一種情況下match(1)="a" bu t在第二種情況下,match(4)="a"(根據需要不是match(1))。實際上,如果你用for g in re.search(myre,teststring2).groups():遍歷所有的組,你得到6個組(不像預期的那樣3個組)。

import re 
import sys 

teststring1 = "abc" 
teststring2 = " a" 

myre = '^(?=(\w)(\w)(\w))|(?=\s{2}(\w)()())' 

if re.search(myre,teststring1): 
    print re.search(myre,teststring1).group(1) 

if re.search(myre,teststring2): 
    print re.search(myre,teststring2).group(1) 

有什麼想法? (注意這是針對Python 2.5的)

回答

5

也許......:

import re 
import sys 

teststring1 = "abc" 
teststring2 = " a" 

myre = '^\s{0,2}(\w)(\w?)(\w?)$' 

if re.search(myre,teststring1): 
    print re.search(myre,teststring1).group(1) 

if re.search(myre,teststring2): 
    print re.search(myre,teststring2).group(1) 

這確實給在這兩種情況下a如你所願,但也許這將不匹配你想在其他情況下,你不顯示(例如沒有空格的方式在前面或空格之後多於一個字母,以便匹配字符串的總長度爲!= 3 ...但我只是猜測你不是想在這種情況下匹配......? )

+0

你說得對 - 這是僅有的兩個案例。正如我所希望的那樣工作。關鍵是有「?」在匹配組(\ w?)內部,以便匹配該字母,或者不匹配任何內容。謝謝! – Mike 2010-06-28 16:14:23

+0

@Mike,不客氣 - 總是樂於幫忙! – 2010-06-28 16:43:47

1
myre = '^(?=\s{0,2}(\w)(?:(\w)(\w))?)' 

這將處理您以您想要的方式描述的兩種情況,但不一定是通用解決方案。感覺就像你想出了一個代表真實的玩具問題。

一個通用的解決方案非常難以實現,因爲稍後元素的處理取決於前一個元素的處理和/或相反。例如,如果您有完整的abc,則最初的空格不應該在那裏。如果最初的空格在那裏,你應該只能找到a

在我看來,處理這個問題的最好方法是使用原來的|構造。你可以在比賽結束後得到一些代碼,將組合放到一個數組中,並根據你的喜好來安排它們。

對於組的規則是全部左括號不會立即跟着?:成爲一個組。該組可能是空的,因爲它實際上沒有匹配任何東西,但它會在那裏。

3

表達式中的每個捕獲組獲取它是自己的索引。試試這個:

r = re.compile("^\s*(\w)(\w)?(\w)?$") 

abc -> ('a', 'b', 'c') 
a -> ('a', None, None) 

進行分解:

^  // anchored at the beginning 
\s* // Any number of spaces to start with 
(\w) // capture the first letter, which is required 
(\w)? // capture the second letter, which is optional 
(\w)? // capture the third letter, which is optional 
$  // anchored at the end