Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.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 如何编写正则表达式以用函数替换%?_Python_Regex - Fatal编程技术网

Python 如何编写正则表达式以用函数替换%?

Python 如何编写正则表达式以用函数替换%?,python,regex,Python,Regex,以下是一些示例输入: B%2==1 N%2!=1 我希望它们相应的输出是: M(B,2)==1 M(N,2)!=1 它看起来很简单,但我无法为此编写正则表达式?请给我一些建议试试这个正则表达式: data= """ B%2==1 N%2!=1 """ rx = r"([A-Z]+)%(\d+)" result = re.sub(rx, r"M(\1,\2)", data, 0, re.IGNORECASE | re.MULTILINE) 它将打印: M(B,2)==1 M(N,2)!=

以下是一些示例输入:

B%2==1
N%2!=1
我希望它们相应的输出是:

M(B,2)==1
M(N,2)!=1
它看起来很简单,但我无法为此编写正则表达式?请给我一些建议

试试这个正则表达式:

data= """
B%2==1
N%2!=1
"""

rx = r"([A-Z]+)%(\d+)"

result = re.sub(rx, r"M(\1,\2)", data, 0, re.IGNORECASE | re.MULTILINE)
它将打印:

M(B,2)==1
M(N,2)!=1

到目前为止,您的正则表达式是什么样子的?捕获带有(\w+)(\w+)的组,替换为M($1,$2),例如
re.sub(r'^(\w+)(\d+)(.*)$),r'M(\1,\2)\3,line)
Hi(如果输入的格式为B%2==1&&N%2=我需要做什么改变?你想要的输出是什么?我想要的输出M(B,2)==1&&M(N,2)=1不确定错误的原因是什么。但是关于正则表达式,请参见