1

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)
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
stratis
  • 7,750
  • 13
  • 53
  • 94

1 Answers1

2

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];'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    I just did a simple replace as @user3203010 also suggested however I'm accepting this one for completeness and the `look around` trick. – stratis Apr 29 '15 at 15:25