Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.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_Python 3.x - Fatal编程技术网

Python 替换主字符串周围的子字符串

Python 替换主字符串周围的子字符串,python,regex,python-3.x,Python,Regex,Python 3.x,我有很多字符串,如下所示: \frac{l_{2}\,\mathrm{phi2dd}\,\sin\left(\varphi _{2}\right)}{2} 我想将\frac{***}{2}替换为\frac{1}{2}*** 然后,所需字符串将变为: \frac{1}{2} l_{2}\,\mathrm{phi2dd}\,\sin\left(\varphi _{2}\right) 我想我可以使用正则表达式来实现这一点,但我不太明白如何从子字符串中提取“主字符串” 更新:我把问题简化得有点过

我有很多字符串,如下所示:

\frac{l_{2}\,\mathrm{phi2dd}\,\sin\left(\varphi _{2}\right)}{2}
我想将
\frac{***}{2}
替换为
\frac{1}{2}***

然后,所需字符串将变为:

\frac{1}{2} l_{2}\,\mathrm{phi2dd}\,\sin\left(\varphi _{2}\right) 
我想我可以使用正则表达式来实现这一点,但我不太明白如何从子字符串中提取“主字符串”


更新:我把问题简化得有点过分了。我必须替换的字符串实际上包含多个“fracs”,如下所示:

I{2}\,\mathrm{phi2dd}-\frac{l{2}\,\mathrm{lm}{4}\,\cos\left(\varphi{2}\ right)}{2}+\frac{l{2}\,\mathrm{lm lm}{3},\sin left(\varphi 2}\ right){0}>

我不知道字符串中发生的次数,这是不同的。

使用
\\frac\{(.*?\}{2}
匹配,并使用
\\frac{1}{2}\1
替换

更新代码:

import re

regex = r"\\frac\{(.*?)\}\{2}"
test_str = "I_{2}\\,\\mathrm{phi2dd}-\\frac{l_{2}\\,\\mathrm{lm}_{4}\\,\\cos\\left(\\varphi _{2}\\right)}{2}+\\frac{l_{2}\\,\\mathrm{lm}_{3}\\,\\sin\\left(\\varphi _{2}\\right)}{2}=0"
subst = "\\\\frac{1}{2} \\1"

# 4th argument decides how many occurences to replace
result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

@hungersoft我在问题陈述中犯了一个错误,我在一个字符串中有多个事件。使用您的解决方案仅替换外部事件,如何替换所有事件?新正则表达式有一个“?”使正则表达式非贪婪并匹配多个事件。