python – Regex match only if odd number of a character precede and follow
So in fact, I think it might be best to only match the groups ” ” and
” + ” if there is an odd number of quotes before and after the group.
Since lookbehing/ahead is fixed length only, I didn’t find a good way
to do it.
If you use re.finditer then you might use .start() and .end() to detect where it does start and end which allows you to get substring and count character, consider following simple example
import re
text="uno " dos " tres " "
for m in re.finditer(r'\s"\s', text):
before = text[:m.start()]
print("Match starting at", m.start(), "and ending at", m.end(), "has", before.count('"'), "quotes in front")
gives output
Match starting at 3 and ending at 6 has 0 quotes in front
Match starting at 9 and ending at 12 has 1 quotes in front
Match starting at 16 and ending at 19 has 2 quotes in front
In your you would need to split your text in lines before applying this solution.
Read more here: Source link
