Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python re.sub():使用特殊字符有困难(可能?)_Python_Regex - Fatal编程技术网

python re.sub():使用特殊字符有困难(可能?)

python re.sub():使用特殊字符有困难(可能?),python,regex,Python,Regex,我想使用re.sub来实现这一点: string = '\\(2 \\, e^{\\left(2 \\, x\\right)} \\sin\\left(2 \\, x\\right) + 2 \\, e^{\\left(2 \\, x\\right)} \\cos\\left(2 \\, x\\right)\\)' 为此: '\\(2 \\, e^{2 \\, x} \\sin\\left(2 \\, x\\right) + 2 \\, e^{2 \\, x} \\cos\\left(2 \\

我想使用re.sub来实现这一点:

string = '\\(2 \\, e^{\\left(2 \\, x\\right)} \\sin\\left(2 \\, x\\right) + 2 \\, e^{\\left(2 \\, x\\right)} \\cos\\left(2 \\, x\\right)\\)'
为此:

'\\(2 \\, e^{2 \\, x} \\sin\\left(2 \\, x\\right) + 2 \\, e^{2 \\, x} \\cos\\left(2 \\, x\\right)\\)'
这是我最好的尝试,但不起作用:

re.sub(r'(?P<left-edge>e\^{\\left\()(?P<input>.*)(?P<right-edge>\\right\)})','e^{\g<input>}',string)

Note that <input> needs to handle an arbitrary expression, while <left-edge> and <right-edge> are fixed character strings. 
re.sub(r'(?Pe\^{\\left\()(?P.*)(?P\\right\)}),'e^{\g},字符串)
请注意,需要处理任意表达式,而和是固定字符串。

我假设这与所涉及的特殊字符有关,但几十次尝试表明这超出了我的专业知识。

正则表达式中的反斜杠必须转义。您使用了
r'
,因此它们不必在Python字符串中作为字符转义,但这还不足以在正则表达式中将它们解释为literal
\
字符。使用双反斜杠:

re.sub(r'(?Pe\^{\\left()(?P.*)(?P\\right)})','e\^{\\g}',string)
如果不是因为
r'
,它们必须被转义两次,即四倍,以满足Python解释器和regexp引擎的要求:

    re.sub('(?Pe\\^{\\\\left()(?P.*)(?P\\\\right)})','e\\^{\\\\g}',string)

(此外,您还忘了转义一个插入符号。我在两个示例中都更正了这一点。)

*
匹配太多:

print(re.sub(r'e\^{\\left\((.*?)\\right\)}', r'e^{\1}', s))

表达式甚至不是有效的正则表达式。您需要
*?
而不是中的
*
\(2 \, e^{2 \, x} \sin\left(2 \, x\right) + 2 \, e^{2 \, x} \cos\left(2 \, x\right)\)