在python中提取分隔符[]之间的单词

2024-05-23 17:41:27 发布

您现在位置:Python中文网/ 问答频道 /正文

从下面的字符串中,我想提取delimeters之间的单词[ ],比如'Service Current','Service','9991','1.22'

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

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

提前谢谢 克里斯


Tags: 字符串nametestevent内容valueservicecurrent
3条回答

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

这通过使用非贪婪匹配来工作,而不是匹配除]之外的任何内容。

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

你可以用正则表达式

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

相关问题 更多 >