您只需要使用re.match
和re.sub
从re
模块,用下面的正则表达式
import re
my_str = 'this is the first part of string 1/32 part this is the second part of string'
my_regex = r'(\d+/\d+\s+part)'
if re.match(my_regex, my_str):
print(re.sub(my_regex, r'\1,', my_str)) # this will print: 1/32 part,
# ...
裸沿如果需要多行来匹配相同的正则表达式,则需要向正则表达式添加一些额外的标志。请参阅here此类标志的列表。
你可以看到正则表达式here
快速更换(有可能是更好的方式)将也部分之前和所需的匹配部分匹配后,做一些事情,如:
import re
my_str = 'this is the first part of string 1/32 part this is the second part of string'
my_regex = r'(.*)(\s+\d+/\d+\s+part)(.*)'
condition = re.match(my_regex, my_str)
if condition:
part = re.sub(my_regex, r'\2,', my_str)
x = condition.group(1) + part + condition.group(3)
print(x)
将输出修改后的字符串:
这是串1/32的第一部分某种程度上,这是 串的第二部分
与所有的一个简单的联机功能上面会:
import re
def modify_string(my_str, my_regex):
return re.sub(my_regex, r'\1,', my_str)
if __name__ == '__main__':
print(modify_string('first part of string 1/32 part second part of string', r'(\d+/\d+\s+part)'))
但我建议你保持状态。 以防万一。
为什么'[1-1000]'?你确切的要求是什么?如果有'/'还有没有关系? –
注意'[1-1000]'是一个*字符组*,因此只会匹配'0'和'1'... –
您只需要匹配'\ d +/\ d + \ s + part' – anubhava