2016-12-02 54 views
1

你好,我試圖解析一個字符串像'2.2.2.2-22' 而使用python re.findall函數我得到兩個組: 我不明白什麼是錯的RE:如何避免在正則表達式中的分組

re.findall(r"([\d.]+(-\d+)?)", "2.2.2.2-22") 

這給我結果爲:[( '2.2.2.2-22', '-22')] 我不想第二組。我怎樣才能解決這個問題?

+1

http://stackoverflow.com/questions/19821487/python-regex-match-or-operator/19821774#19821774 – hwnd

+0

查找Python正則表達式問題的好地方是https://docs.python.org/3 /library/re.html – lxop

回答

4

爲了避免分組可以使用?:

>>> import re 
>>> re.findall(r"([\d.]+(?:-\d+)?)", "2.2.2.2-22") 
['2.2.2.2-22'] 

這將迫使該集團存在,但它不會趕上並返回值。

+0

@hwnd將不會捕獲字符串OP後 – lxop