简体   繁体   English

正则表达式搜索并替换Python中的子字符串

[英]Regex search and replace substring in Python

I need some help with a regular expression in python. 我需要一些有关python中的正则表达式的帮助。

I have a string like this: 我有一个像这样的字符串:

>>> s = '[i1]scale=-2:givenHeight_1[o1];'

How can I remove givenHeight_1 and turn the string to this? 如何删除givenHeight_1并将字符串转换为此?

>>> '[i1]scale=-2:360[o1];' 

Is there an efficient one-liner regex for such a job? 是否有有效的单行正则表达式来完成这项工作?

UPDATE 1: my regex so far is something like this but currently not working: 更新1:到目前为止,我的正则表达式是这样的,但目前无法正常工作:

re.sub('givenHeight_1[o1]', '360[o1]', s)

You can use positive look around with re.sub : 您可以对re.sub使用正面look around

>>> s = '[i1]scale=-2:givenHeight_1[o1];'
>>> re.sub(r'(?<=:).*(?=\[)','360',s)
'[i1]scale=-2:360[o1];'

The preceding regex will replace any thing that came after : and before [ with an '360' . 前面的正则表达式将取代来到之后的任何事情:之前['360'

Or based on your need you can use str.replace directly : 或者根据您的需要,可以直接使用str.replace

>>> s.replace('givenHeight_1','360')
'[i1]scale=-2:360[o1];'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM