2010-05-17 57 views
7

從下面的字符串,我想提取delimters [ ]'Service Current','Service','9991','1.22'的話:提取定界符之間字[]在Python

str='mysrv events Generating Event Name [Service Current], Category [Service] Test [9991] Value [1.22]' 

我怎樣才能提取蟒蛇一樣嗎?

預先感謝 克里斯

回答

18

首先,避免使用str作爲變量名。 str在Python中已經有了含義,並且將其定義爲別的東西會讓人困惑。

說了這麼多,你可以使用下面的正則表達式:

>>> import re 
>>> print re.findall(r'\[([^]]*)\]', s) 
['Service Current', 'Service', '9991', '1.22'] 

這種工作方式如下:

 
\[ match a literal [ 
( start a capturing group 
[^]] match anything except a closing ] 
* zero or more of the previous 
) close the capturing group 
\] match a literal ] 

另一種正則表達式爲:

r'\[(.*?)\]' 

這是通過使用非貪婪匹配而不是匹配除之外的任何內容0。

+2

+ 1的表達變成,如果你只是使它非貪婪簡單:''\\ [\\(。*?)。 [鏈接到're.findall()'](http://docs.python.org/library/re.html#re.findall),[鏈接到're'](http://docs.python.org /library/re.html) – 2010-05-17 20:29:52

+0

@Felix:新增,謝謝。 – 2010-05-17 20:30:42

+0

這些表達式也會匹配字符串''[]'',並返回'['']'(空字符串)。如果在它們之間沒有字符的方括號應該被忽略,那麼'*'可以在第一個表達式中改爲'+'。即,'r'\ [([^]] +)\]''。 (有趣的是,在非貪婪表達式中替換'*'似乎不起作用。) – jpmc26 2013-01-16 23:30:40

2
re.findall(r'\[([^\]]*)\]', str) 
4

你可以使用正則表達式

import re 
s = re.findall('\[(.*?)\]', str) 
+0

嘿,我很努力地理解這個,我將如何修改該代碼以從中提取單詞('word°',) ('和')是否有任何有用的教程可以引導我 – 2018-02-13 19:40:32

相關問題