Skip to content

Instantly share code, notes, and snippets.

@thiborose
Created December 9, 2022 13:13
Show Gist options
  • Select an option

  • Save thiborose/73a3e352cf14f84edf6a0d09323c166f to your computer and use it in GitHub Desktop.

Select an option

Save thiborose/73a3e352cf14f84edf6a0d09323c166f to your computer and use it in GitHub Desktop.
replace each occurence of a regex pattern with a different value
# example - replace all occurences of 4 digits with 4 new random digits in an XML file
import random
import re
content = open("in.xml", "r", encoding="utf-8").read()
numbers = '(one|two|three|four|five|six|seven|eight|nine|zero|null)'
pattern = re.compile(f'{numbers}\s{numbers}\s{numbers}\s{numbers}')
def get_new_value():
return " ".join([random.choice(["one","two","three","four","five","six","seven","eight","nine","zero","null"]) for _ in range(4)])
cursor = 0
new_string = ""
for m in re.finditer(pattern, content):
match_start, match_end = m.span()
new_string += content[cursor:match_start]
rep = get_new_value()
new_string += rep
cursor = match_end
new_string += content[cursor:]
open("out.xml", "w", encoding="utf-8").write(new_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment