[英]Extracting words between delimiters [] in python
From the below string, I want to extract the words between delimters [ ]
like 'Service Current','Service','9991','1.22'
: 从下面的字符串中,我想提取分隔符
[ ]
之间的单词,如'Service Current','Service','9991','1.22'
:
str='mysrv events Generating Event Name [Service Current], Category [Service] Test [9991] Value [1.22]'
How can I extract the same in python? 如何在python中提取相同的内容?
Thanks in advance Kris 在此先感谢Kris
First, avoid using str
as a variable name. 首先,避免使用
str
作为变量名。 str
already has a meaning in Python and by defining it to be something else you will confuse people. str
已经在Python中具有意义,并且通过将其定义为其他东西,您将会混淆人们。
Having said that you can use the following regular expression: 说过你可以使用以下正则表达式:
>>> import re
>>> print re.findall(r'\[([^]]*)\]', s)
['Service Current', 'Service', '9991', '1.22']
This works as follows: 其工作原理如下:
\[ 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 ]
An alternative regular expression is: 另一种正则表达式是:
r'\[(.*?)\]'
This works by using a non-greedy match instead of matching anything except ]
. 这通过使用非贪婪的匹配而不是匹配除了
]
之外的任何东西来工作。
you can use regex 你可以使用正则表达式
import re
s = re.findall('\[(.*?)\]', str)
re.findall(r'\[([^\]]*)\]', str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.