Created
December 9, 2022 13:13
-
-
Save thiborose/73a3e352cf14f84edf6a0d09323c166f to your computer and use it in GitHub Desktop.
replace each occurence of a regex pattern with a different value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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