Here is an approach you can use to achieve this. Explanations as part of code itself.
import re
def replace(content, replace_with, prefix="apple"):
"""
with re, find the pattern (?<=apple\.)("\d+"), and find the numerical to replace
replace it with the random value you want.
Do this for every line in your text.
:param content: The text content, read from file or whatever pass it as a string
:param replace_with: the value you want to replace the value with.
:param prefix: the text before the number, default is apple.
:return: the content with the replaced value
"""
# The regex used was (?<=apple\.)("\d+"), which is a lookbehind assertion
# that matches the text "apple." and then a group of digits.
return "\n".join([re.sub(rf'(?<={prefix}\.)("\d+")', f'"{replace_with}"', line) for line in content.split("\n")])
text = '''
{
9apple."234"
orangetaco""
testrocket""
3apple."923"
mangofruit""
1apple."148"
}
'''
print(replace(text, 345, "apple"))
This will give you a transformed text like
{
9apple."345"
orangetaco""
testrocket""
3apple."345"
mangofruit""
1apple."345"
}
You can also refer this answer, to learn more about the regex that was used.