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

2 に答える 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'
于 2012-06-03T20:47:01.380 に答える
0

foo の内容には括弧が含まれていないと言うので、正規表現は本当に必要ないようです。やってみませんか:

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

Python: string.replace と re.subを参照してください。

于 2012-06-03T21:45:18.217 に答える