2

I have this string in Python:

s = "foo(a) foo(something), foo(stuff)\n foo(1)"

I want to replace every foo instance with its content:

s = "a something, stuff\n 1"

The string s is not constant and the foo content changes every time. I did something using regex, split and regex, but got a very large function. How can I do it in a simple and concise way? Thks in advance.

4
  • s.replace("foo", "a something, stuff\n 1") Commented Jun 3, 2012 at 20:41
  • 1
    What values of x are allowed inside foo(x)? Are parentheses allowed, i.e. foo(hello (there))? If not, this should be simple with capturing groups Commented Jun 3, 2012 at 20:43
  • Nick ODell: foo content changes every time. it's unknown. Commented Jun 3, 2012 at 20:43
  • matt b: Great question. Does not allow parentheses. It allows identificators (essentially word) Commented Jun 3, 2012 at 20:45

2 Answers 2

6
>>> x = "foo(a) foo(something), foo(stuff)\n foo(1)"
>>> re.sub(r'foo\(([^)]*)\)', r'\1', x)
u'a something, stuff\n 1'
Sign up to request clarification or add additional context in comments.

Comments

0

Since you say that the content of foo doesn't contain parentheses, Regex really doesn't seem needed. Why don't you just do:

>>> s = "foo(a) foo(something), foo(stuff)\n foo(1)"
>>> s = s.replace('foo(','')
>>> s = s.replace(')','')
>>> print s
'a something, stuff\n 1'

See Python: string.replace vs re.sub

Comments

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.