patternpythonMinor
Replace match inside tags
Viewed 0 times
matchtagsreplaceinside
Problem
The problem I want to solve is to replace a given string inside tags.
For example, if I'm given:
Some text abc [tag]some text abc, more text abc[/tag] still some more text
I want to replace
Some text abc [tag]some text def, more text def[/tag] still some more text
We may assume that the tag nesting is well formed. My solution is the following:
I was wondering if it can be solved in a more elegant way, for example, using regex.
For example, if I'm given:
Some text abc [tag]some text abc, more text abc[/tag] still some more text
I want to replace
abc for def but only inside the tags, so the output would be:Some text abc [tag]some text def, more text def[/tag] still some more text
We may assume that the tag nesting is well formed. My solution is the following:
def replace_inside(text):
i = text.find('[tag]')
while i >= 0:
j = text.find('[/tag]', i+1)
snippet = text[i:j].replace('abc', 'def')
text = text[:i] + snippet + text[j:]
i = text.find('[tag]', j)
return textI was wondering if it can be solved in a more elegant way, for example, using regex.
Solution
Your code is incorrect. See the following case:
You can indeed use regular expressions
print replace_inside("[tag]abc[/tag]abc[tag]abc[/tag]")You can indeed use regular expressions
pattern = re.compile(r"\[tag\].*?\[/tag\]")
return pattern.sub(lambda match: match.group(0).replace('abc','def') ,text)Code Snippets
print replace_inside("[tag]abc[/tag]abc[tag]abc[/tag]")pattern = re.compile(r"\[tag\].*?\[/tag\]")
return pattern.sub(lambda match: match.group(0).replace('abc','def') ,text)Context
StackExchange Code Review Q#9072, answer score: 2
Revisions (0)
No revisions yet.