Question: I'm using Python to write a regular expression for replacing parts of the string with a XML node.

The source string looks like:

```

Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace

```

And the result string should be like:

```

Hello
<replace name="str1"> this is to replace </replace>
<replace name="str2"> this is to replace </replace>

```

Can anyone help me?

Answer: 
Here is a solution using pyparsing. I know you specifically asked about a regex solution, but if your requirements change, you might find it easier to expand a pyparsing parser. Or a pyparsing prototype solution might give you a little more insight into the problem leading toward a regex or other final implementation.

```
src = """\
Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace
"""

from pyparsing import Suppress, Word, alphas, alphanums, restOfLine

LPAR,RPAR = map(Suppress,"()")
ident = Word(alphas, alphanums)
replExpr = "REPLACE" + LPAR + ident("name") + RPAR + restOfLine("body")
replExpr.setParseAction(
    lambda toks : '<replace name="%(name)s">%(body)s </replace>' % toks
    )

print replExpr.transformString(src)

```

In this case, you create the expression to be matched with pyparsing, define a parse action to do the text conversion, and then call transformString to scan through the input source to find all the matches, apply the parse action to each match, and return the resulting output. The parse action serves a similar function to mksub in @steveha's solution.

In addition to the parse action, pyparsing also supports naming individual elements of the expression - I used "name" and "body" to label the two parts of interest, which are represented in the re solution as groups 1 and 2. You *can* name groups in an re, the corresponding re would look like:

```
s_pat = "^\s*REPLACE\((?P<name>[^)]+)\)(?P<body>.*)$"

```

Unfortunately, to access these groups by name, you have to invoke the `group()` method on the re match object, you can't directly do the named string interpolation as in my lambda parse action. But this is Python, right? We can wrap that callable with a class that will give us dict-like access to the groups by name:

```
class CallableDict(object):
    def __init__(self,fn):
        self.fn = fn
    def __getitem__(self,name):
        return self.fn(name)

def mksub(m):    
    return '<replace name="%(name)s">%(body)s</replace>' %  CallableDict(m.group)

s_output = re.sub(pat, mksub, s_input)

```

Using `CallableDict`, the string interpolation in mksub can now call m.group for each field, by making it look like we are retrieving the ['name'] and ['body'] elements of a dict.
```
import re

a="""Hello
REPLACE(str1) this is to replace
REPLACE(str2) this is to replace"""

regex = re.compile(r"^REPLACE\(([^)]+)\)\s+(.*)$", re.MULTILINE)

b=re.sub(regex, r'< replace name="\1" > \2 < /replace >', a)

print b

```

will do the replace in one line.