How to extract tags with% delimiters

I want to get %tagname%

from a file and copy them only to a dictionary tagname

in python.

+2


a source to share


2 answers


this will give you a list of tags



re.findall("%([^%]+)%", text)

      

+7


a source


To get a list of tags, you can use the unwanted version of the + operator, which has the advantage of being simple:

re.findall('%(.+?)%', text)

      

In fact, it .+?%

finds all characters of any type (tag) and stops as soon as it finds it %

(which is the "non-greedy" part).



In the speed test below, the non-greedy version of this answer is slower than the "no other% sign" version by almost 2 times:

python -m timeit -s'import re; t="%t1% lkj lkj %long tag% lkj lkj"*1000' 're.findall("%([^%]+)%", t)'
1000 loops, best of 3: 874 usec per loop

python -m timeit -s'import re; t="%t1% lkj lkj %long tag% lkj lkj"*1000' 're.findall("%(.+?)%", t)'
1000 loops, best of 3: 1.43 msec per loop

      

+2


a source







All Articles