简体   繁体   English

python中的多个正则表达式匹配

[英]Multiple regex matching in python

I am new to regex in python, while the simple cases are a breeze, I am having troubles extracting multiple words from a string using. 我是python中的regex的新手,虽然简单的情况很容易,但是我在使用字符串提取多个单词时遇到了麻烦。 The string looks like this: 该字符串如下所示:

lyne = "| 0x008d | 2345| 0xe54b5b42 | 0520 | 0x02 GREEN| 4 RED |" lyne =“ | 0x008d | 2345 | 0xe54b5b42 | 0520 | 0x02绿色| 4红色|”

and access the different substrings between the | 并访问|之间的不同子字符串。 | | using match.group 使用match.group

is there a way to do this...can anyone please help 有办法吗...有人可以帮忙吗

Thanks 谢谢

无需正则表达式:

substrs = [x.strip() for x in lyne.split('|') if x]

Any reason you can't just use lyne.split('|') which'll do it, otherwise use re.split() with the same thing... 任何原因都不能只使用lyne.split('|')完成,否则请使用re.split()进行相同的操作...

If you really want a regexp (to match/find instead of split), then (stripping out spaces): 如果您确实想要一个正则表达式(匹配/查找而不是拆分),则(去除空格):

>>> re.findall(r'\|?\s*(.*?)\s*\|', lyne)
['0x008d', '2345', '0xe54b5b42', '0520', '0x02 GREEN', '4 RED']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM