2013-06-13 88 views
0

如何匹配這樣的串串:正則表達式如何匹配包含方括號

firstword [foo = bar] 

firstword 

使用1個正則表達式。

我已經試過是(\w+)[\s]{0,1}\[(.+)\]和我只能匹配第一個,我也被包裹的最後一個\[(.+)\][]*[\[(.+)\]]*嘗試,現在我不能在方括號內匹配的空白和「=」。

你們可以給個提示嗎?

回答

3

好像最後一部分是根本可選:

(\w+)\s?(?:\[([^\]]+)\])? 

(?: ...)?是不執行內存捕獲的可選部分。

如果可選部分也意味着總會有一個空間,你可以移動\s裏面還有:

(\w+)(?:\s\[([^\]]+)\])? 
0
(\w+)\s*(\[.+?\])? 

測試在Python交互shell:

>>> re.match(r'(\w+)\s*(\[.+?\])?', 'firstword [foo = bar]').groups() 
('firstword', '[foo = bar]') 
>>> re.match(r'(\w+)\s*(\[.+?\])?', 'firstword [foo = bar').groups() 
('firstword', None) 
>>> re.match(r'(\w+)\s*(\[.+?\])?', 'firstword foo = bar').groups() 
('firstword', None) 
>>> re.match(r'(\w+)\s*(\[.+?\])?', 'firstword foo = bar]').groups() 
('firstword', None) 
>>> re.match(r'(\w+)\s*(\[.+?\])?', 'firstword').groups() 
('firstword', None) 
0

你可以使用非qreedy量詞。在Perl擴展表示法中:

s/^  # Beginning of string. You might not need this. 
    (\w+) # Capture a word. 
    \s*  # Optional spaces. 
    (?:  # Non-capturing group. 
     \[  # Literal bracket. 
     .*?  # Any number of characters, but as few as possible, 
       # so stopping before: 
     \]  # Literal bracket 
    )?   # End the group, and make it optional as requested. 
/
    $1  # The captured word. 
/x   # Allow the extended notation. 

根據需要進行修改。一些引擎使用\1而不是$1

+0

這個正則表達式不會使括號內的選項。 – ibi0tux

+0

正確。我將編輯我的答案。另一方面,如果正則表達式不匹配,反正沒有任何事情要做。 –