ele lont
ele lont

Reputation: 479

Replace with re.sub AFTER matching pattern

i have a regex substitution that i cannot figure out.

s2 = re.compile("^DATA_ARRAY (.*?};)", re.DOTALL|re.MULTILINE)    
result = re.sub(s2, "newData", inputData)

The problem is that it replaces the "DATA_ARRAY" part as well. I need to replace only the text that comes AFTER the "DATA_ARRAY" part. I have placed the data in a group in the s2 (.*?};)but cannot figure out how to use the re.sub function to replace only the required part.

Regards

Upvotes: 2

Views: 1089

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

s2 = re.compile("(?<=^DATA_ARRAY )(.*?};)", re.DOTALL|re.MULTILINE)    
result = re.sub(s2, "newData", inputData)

You can just have a lookbehind assertion (?<=___).

Upvotes: 0

vks
vks

Reputation: 67968

s2 = re.compile("^(DATA_ARRAY )(.*?};)", re.DOTALL|re.MULTILINE)    
result = re.sub(s2, r"\1newData", inputData)

You can capture the first group and replace via backreferencing

or simply

s2 = re.compile("^DATA_ARRAY (.*?};)", re.DOTALL|re.MULTILINE)    
result = re.sub(s2, "DATA_ARRAY newData", inputData)

Upvotes: 2

Related Questions