简体   繁体   English

如何在python中正则表达式一个空字符串?

[英]How regex a empty string in python?

I want that find empty tags, here is a example 我希望找到空标签,这是一个示例

txt ="<lol1><><lol2>"
rgx = "<([a-zA-Z_0-9]+)>"
print re.findall(rgex, txt)

I get this 我明白了

['lol1', 'lol2']

I want 我想要

['lol1', '', 'lol2']

How I can do this with regex? 我如何用正则表达式来做到这一点?

Use rgx = "<([a-zA-Z_0-9]*)>" 使用rgx = "<([a-zA-Z_0-9]*)>"

The key point is using * , which means "zero or more of the preceding", where you're using + , which means "one or more". 关键是使用* ,表示“零个或多个以上”,而使用+表示“一个或多个”。

no need regex 无需正则表达式

>>> s="txt ="<lol1><><lol2>"
>>> for i in txt.split(">"):
...     if "<" in i:
...        print i[i.find("<")+1:]
...
lol1

lol2
>>> [i[i.find("<")+1:] for i in txt.split(">") if "<" in i ]
['lol1', '', 'lol2']

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

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