1

I am new to python and I have been trying to check and substitute a specific value for a string. To illustrate, let me paste the bit of code that I used:-

 var1 = re.sub(r'\$this->getSomething()->getSomethingElse()->(.*?)', r'\1', var1)

What I am trying to do here is to replace the entire string(var1) with the value contained within (.*?). E.g if the string is in this format "$this->getSomething()->getSomethingElse()->__('Title')" then the new value for var1 should be "__('Title')." At the moment I can't figure out what's wrong with the code and I tried searching all over the place including stackoverflow but not to avail.

Note : This seems to work well though :-

value = re.sub(r"\$title", "$this->title", value)

I hope someone can help me with this problem or at least direct me in the right direction. Thanks in advance.

2
  • Any particular reason you're using reluctant matching? Commented Feb 21, 2011 at 5:50
  • No any specific reasons. Was trying through many solutions which was posted online. The problem was I didn't escape the parentheses. Thanks for your extremely fast response. Saved me from hours more of searching. Commented Feb 21, 2011 at 6:07

1 Answer 1

1

Parentheses are metacharacters, used for grouping. You also want to match literal parentheses, which means you need to escape some instances. Try:

var1 = re.sub(r'\$this->getSomething\(\)->getSomethingElse\(\)->(.*?)', r'\1', var1)

Note that this particular statement is equivalent to:

var1 = re.sub(r'\$this->getSomething\(\)->getSomethingElse\(\)->', '', var1)

and:

var1 = var1.replace('$this->getSomething()->getSomethingElse()->', '')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the help. It worked well. I realized what I was doing wrong and thanks again for the alternative solutions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.