0

How would I replace groups found using the python regex findall method without having to change the rest of the string too.

For example:

import re
repl1='k1'
repl2='k2'
pattern=re.compile('CN=Root,Model=.*,Vector=Reactions\[(.*)\],ParameterGroup=Parameters,Parameter=(.*),Reference=Value')

I want use the re.sub to replace ONLY the elements within the (.*) with repl1 and repl1 rather than having to change the rest of the string too.

-------edit -----

The output I want should look like this:

output = 'CN=Root,Model=.*,Vector=Reactions[k1],ParameterGroup=Parameters,Parameter=k2,Reference=Value')

But note I have left the '.*' in after model because this will change every time. I.e. this can be anything.

----------edit 2----------

The input is a simple one line which is almost exactly the same at pattern. For example:

input= 'CN=Root,Model=Model1,Vector=Reactions\[k10],ParameterGroup=Parameters,Parameter=k12,Reference=Value')
6
  • 5
    An example along with expected output would be better. Aug 18, 2015 at 11:02
  • No problem - I've made some edits Aug 18, 2015 at 11:17
  • Should there always be one replacement each for repl1 and repl2 or how do you intend to distinguish when each should be replaced? Aug 18, 2015 at 11:21
  • Like this? Aug 18, 2015 at 11:24
  • Yes, repl1 and repl2 are always only one item long (if this is what you mean). I'm using this within a loop over many files (eventually) but only concerning myself with one replacement at the moment Aug 18, 2015 at 11:32

1 Answer 1

3

re.sub's argument repl can be a one-argument function, and in that case it is called with the match object as an argument. So, if you ensure that all parts of the pattern are in a group you should have all the information you need to replace the old string with the new one.

import re

repl1='k1'
repl2='k2'
pattern=re.compile('(CN=Root,Model=.*,Vector=Reactions\[)(.*)(\],ParameterGroup=Parameters,Parameter=)(.*)(,Reference=Value)')
target = 'CN=Root,Model=something,Vector=Reactions[somethingelse],ParameterGroup=Parameters,Parameter=1234,Reference=Value'

Now define a function that produces the matched string with groups 1 and 3 replaced with your desired values:

def repl(m):
    g = list(m.groups())
    g[1] = repl1
    g[3] = repl2
    return "".join(g)

Passing this function as the first argument to re.sub than achieves the desired transformation:

pattern.sub(repl, target)

gives the result

'CN=Root,Model=something,Vector=Reactions[k1],ParameterGroup=Parameters,Parameter=k2,Reference=Value'

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.