[英]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: 我想在Python中使用以Perl编写的正则表达式为:
$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). 我还需要提取捕获组(Perl中
$1
)。
In python you use re.sub
instead of perl s///
operator. 在python中,您使用
re.sub
而不是perl s///
运算符。 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. 不需要
\\
转义的“原始字符串”的特殊语法(如r'\\')将为您提供帮助。 A substitution comes as a second argument, you also use \\1
instead of $1
for backref. 替换作为第二个参数,您还使用
\\1
而不是$1
进行反向引用。 There is no such thing as topic variable in python, so you need to explicitly pass source string as a third argument. python中没有主题变量之类的东西,因此您需要显式传递源字符串作为第三个参数。 Then you add regular expression flags as dedicated named argument, their values are stored in
re.I
, re.S
, ... constants. 然后添加正则表达式标志作为专用的命名参数,它们的值存储在
re.I
, re.S
,...常量中。 You don't need g
flag as re.sub
is global by default: 您不需要
g
标志,因为re.sub
在默认情况下是全局的:
import re
text = re.sub(r'\[\[category:([^|\]]*)[^]]*\]\]', '[[\1]]',
text, flags=re.I)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.