Alquimista
Alquimista

Reputation: 872

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?

Upvotes: 2

Views: 4919

Answers (2)

ghostdog74
ghostdog74

Reputation: 342649

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']

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 882133

Use 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".

Upvotes: 8

Related Questions