Skip to main content
gamedev.net
🔒 Locked

python regular expression - all but substring?

Started by gnomer 1 reply 3.3k views
Original Post
gnomer
gnomer
I'm trying to figure out these regular expressions =( I'm trying to match all the text on a line that is not followed by "</xyz>". If it's not followed by that get next line and keep matching lines until it finds "</xyz>". How can I do this? I've tried a few variations but I can't figure it out. The below does not work.

p = re.compile(r"""

    (?P<id>(.*(?!</xyz>)\s*)*)

    """, re.VERBOSE)


Zahlman
Zahlman
Quote:
S
DOTALL
Makes the "." special character match any character at all, including a newline; without this flag, "." will match anything except a newline.


Then all you want to do is match everything up until the first </xyz>. To do that, we need to be aware of the fact that regexes are greedy by default, and that we don't want that behaviour here (since if we just match "zero or more of anything" followed by the tag, then we'll match everything until the *last* occurrence of the tag). So we just use a non-greedy quantifier to get around that.

Thus,

p = re.compile('(?P<id>.*?)</xyz>', re.DOTALL)
gnomer
gnomer
Thanks Zahlman. I ended up getting it to work a bit different. It's good to see it another way and helps me understand. :)

Here is what I used:

(?P<id>( .(?!/xyz>)\s* )*)

Yours looks much better :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.