簡體   English   中英

在python中提取分隔符[]之間的單詞

[英]Extracting words between delimiters [] in python

從下面的字符串中,我想提取分隔符[ ]之間的單詞,如'Service Current','Service','9991','1.22'

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

如何在python中提取相同的內容?

在此先感謝Kris

首先,避免使用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'\[(.*?)\]'

這通過使用非貪婪的匹配而不是匹配除了]之外的任何東西來工作。

你可以使用正則表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM