简体   繁体   中英

How do I translate this perl regex into python?

I would like to use a regular express in Python that is written in Perl as:

$text =~ s/\[\[category:([^|\]]*)[^]]*\]\]/[[$1]]/ig;

Anyone has an idea about how to do that? I will also need to extract the capture group ( $1 in Perl).

In python you use re.sub instead of perl s/// operator. You give it regular expression string as a first argument. A special syntax for "raw strings" which don't need \\ escaped, like r'\\', will help you. A substitution comes as a second argument, you also use \\1 instead of $1 for backref. There is no such thing as topic variable in python, so you need to explicitly pass source string as a third argument. Then you add regular expression flags as dedicated named argument, their values are stored in re.I , re.S , ... constants. You don't need g flag as re.sub is global by default:

import re
text = re.sub(r'\[\[category:([^|\]]*)[^]]*\]\]', '[[\1]]', 
              text, flags=re.I)

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