简体   繁体   English

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

[英]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.

相关问题 在python中区分分隔符[[]]和[[]]之间的单词 - Distinguish words between delimiters [[ ]] and [[ ]]s in python 将分隔符之间的文本文件行提取到列表Python中 - Extracting lines of a text file between delimiters into a list Python 当分隔符采用不同格式时,使用 Python 在两个分隔符之间提取文本 - Extracting text between two delimiters when the delimiters are in different formats using Python Python Regex:两个定界符之间的单词-用标点符号替换前导定界符,但删除结尾的定界符 - Python Regex: words between two delimiters - replace leading delimiters with punctuation, but removing ending ones 使用自定义分隔符从大型文本文件中提取特定分隔符之间的部分文本,然后使用Python将其写入另一个文件 - Extracting parts of text between specific delimiters from a large text file with custom delimiters and writing it to another file using Python 重复分隔符并提取它们之间的字符串 - Repeating delimiters and extracting the string between those 提取一行中两个定界符之间的多次出现 - Extracting multiple occurrences between 2 delimiters in a line 在PYTHON中提取标签中的单词 - Extracting in words in tags in PYTHON 如何删除两个分隔符之间的单词? - How to delete the words between two delimiters? 拆分字符串以在定界符之间查找单词? - Splitting a string to find words between delimiters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM