简体   繁体   中英

Regex search and replace substring in Python

I need some help with a regular expression in 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?

>>> '[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:

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

You can use positive look around with re.sub :

>>> 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' .

Or based on your need you can use str.replace directly :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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