Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, list everything between two tags

I'm looking for the shortest neatest way to code the folloing.

say I have a string containing: 'the f<ox jumpe>d over the l<azy> dog <and the >fence'

Using < as the opening tag and > as the closing tag, I would like to save everything inbetween into a list.

if saved into list1, list1 would equal ['ox jumpe', 'azy', 'and the ']

Who knows of a nice, neat SHORT way to do this.

Thanks!

like image 216
Rhys Avatar asked Sep 11 '26 11:09

Rhys


1 Answers

Regular expressions should do the trick here:

import re

text = 'the f<ox jumpe>d over the l<azy> dog <and the >fence'
list = re.findall('.*?\<(.*?)\>.*?', text)

print list

Edit:

You can read more about regex here

Mainly, what the regex from above does is:

.*? - non greedy match of all the characters until next wanted char

\< - matches the < char

(.*?) - non greedy match of all the characters until next wanted char, capture and returns them

like image 79
Tudor Constantin Avatar answered Sep 14 '26 00:09

Tudor Constantin