I want to get the %tagn开发者_运维百科ame%
from a file and copy them to a dictionary only tagname
in python.
this will get you a list of tags
re.findall("%([^%]+)%", text)
To get the list of tags, you can use the non-greedy version of the + operator, which has the advantage of being simple:
re.findall('%(.+?)%', text)
In fact, .+?%
finds all characters of any type (a tag), and stops as soon as %
is found (that's the "non-greedy" part).
In the speed test below, the non-greedy version of this answer is slower than the "not another % sign" version by a factor of almost 2, though:
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
精彩评论