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)
4
  • Are you going to post your regex? Also, where did _1 go?
    – vaultah
    Commented Apr 29, 2015 at 15:08
  • 2
    Have you tried the simple string.replace? s.replace("givenHeight_1","360") Commented Apr 29, 2015 at 15:13
  • 1
    As @user3203010 mentions, string.replace seems better here. See stackoverflow.com/questions/5668947/…
    – matiasg
    Commented Apr 29, 2015 at 15:16
  • @user3203010 Well that did the job! Thanks.
    – stratis
    Commented Apr 29, 2015 at 15:24

1 Answer 1

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];'
1
  • 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
    Commented Apr 29, 2015 at 15:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.