简体   繁体   中英

Regular Expression (regex) Pattern Matching in Python

My regular expression in python is as follows:

\\newcommand\\shortpage[.*?][.*?]{.*?{.*?}}

The text I am trying to match is:

\newcommand\shortpage[1][1]{\enlargethispage*{-#1\baselineskip}} % see Latex Companion, 2nd ed., p. 234

How do I fix my regular expression so that it properly matches my text?

Thank you.

Brackets and braces are metacharacters, you need to escape them:

\\newcommand\\shortpage\[.*?\]\[.*?\]\{.*?\{.*?\}\}

Actually, many regex engines don't require you to escape braces if it can be inferred from context that they aren't used as quantifiers (as in x{2,4} ), but it's better to be explicit.

Furthermore, .* and .*? should be replaced, if possible, with something more specific than "match anything":

\\newcommand\\shortpage\[[^\]]*\]\[[^\]]*\]\{[^}]*\{[^}]*\}\}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM