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.

Academia
  • 3,984
  • 6
  • 32
  • 49

2 Answers2

6
>>> x = "foo(a) foo(something), foo(stuff)\n foo(1)"
>>> re.sub(r'foo\(([^)]*)\)', r'\1', x)
u'a something, stuff\n 1'
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
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

Community
  • 1
  • 1
Junuxx
  • 14,011
  • 5
  • 41
  • 71