Skip to content Skip to sidebar Skip to footer

Split String On Portion Of Matched Regular Expression (python)

Say I have a string 'ad>ad>ad>>ad' and I want to split on this on the '>' (not the '>>' chars). Just picked up regex and was wondering if there is a way (speci

Solution 1:

You need to use lookarounds:

re.split(r'(?<!>)>(?!>)', 'ad>ad>ad>>ad')

See the regex demo

The (?<!>)>(?!>) pattern only matches a > that is not preceded with a < (due to the negative lookbehind (?<!>)) and that is not followed with a < (due to the negative lookahead (?!>)).

Since lookarounds do not consume the characters (unlike negated (and positive) character classes, like [^>]), we only match and split on a < symbol without "touching" the symbols around it.


Post a Comment for "Split String On Portion Of Matched Regular Expression (python)"