I would like to select a text from a file in Python and replace only from the selected phrase until a certain text.
with open ('searchfile.txt', 'r' ) as f:
content = f.read()
content_new = re.sub('^\S*', '(.*?\/)', content, flags = re.M)
with open ('searchfile.txt', 'w') as f:
f.write(content_new)
searchfile.txt contains the below text:
abc/def/efg 212 234 asjakj
hij/klm/mno 213 121 ashasj
My aim is to select everything from the line until the first space and then replace it with the text until the first occurance of backslash /
Example:
^\S* selects everything until the first space in my file which is "abc/def/efg".
I would like to replace this text with only "abc" and "hij" in different lines
My regexp (.*?\/) does not work for me here.
re.sub()isn't a regular expression, it's the replacement text. Only the first argument is a regexp.content_new = content.split()[0].split('/')[0], why regex?abc/def/efg 212 234 asjakj" - it means there is only one line.