2017-04-20 37 views
0

我知道這是一個非常常見的問題,但它讓我很生氣。用正則表達式提取子字符串python

我想使用正則表達式匹配我的字符串中的子字符串。

line = '##ParameterValue[part I care about]=garbagegarbage' 

我想提取part I care about。 我的代碼如下所示:

import re 
line = '##ParameterValue[part I care about]=garbagegarbage' 
m = re.match('\[(.*)\]', line) 
print m.group(1) 

但是這給了我一個AttributeError: 'NoneType' object has no attribute 'group'

我測試了我的正則表達式上regex101和它的作品。我不明白爲什麼這對我不合適。

+2

你是對的,這是過於頻繁的問題。 –

+1

嘗試['search'](https://docs.python.org/2/library/re.html#re.search)。 ['match'](https://docs.python.org/2/library/re.html#re.match)正在尋找匹配從字符串的開頭。 –

回答

0

變化matchsearch

import re 
line = '##ParameterValue[part I care about]=garbagegarbage' 
m = re.search('\[(.*)\]', line) 
print m.group(1)