bash - How to delete shortest matched pattern from the end of string by re module of python? -
i converting bash code python code.
now make function has same functionality of ${variable%pattern} in bash; delete shortest matched pattern end of string,
for example, expect delete_tail('_usr_home_you_file.ext.tar.oz', r'.') results in '_usr_home_you_file.ext.tar'
i made python function below,
import re def delete_tail(word,pattern): return re.sub('{0}.*?$'.format(pattern), '', word)
however, deletes longest matched pattern following.
word='_usr_home_you_file.ext.tar.oz' delete_shortest_match_tail=delete_tail(word,r'\.') print("word = {0}".format(word)) print("delete_shortest_match_tail = {0}". format(delete_shortest_match_tail))
output:
delete_shortest_match_tail = _usr_home_you_file
how can make function deletes shortest matched pattern end of string expected above?
thank much.
you rather want search string in front of pattern rather pattern replace it. regex looks left right , matches reported in order. can't reverse strings, because mess regex pattern. because of can't use sub
, replacing empty string same deleting, or taking rest of string. solution does. searches result , omits part don't want.
def removefromend(pattern, target): m = re.match("(.*)" + pattern + ".*$", target) if m: return m.group(0) else: return target
>>> removefromend("\.", "foo.tar.gz")
'foo.tar'
Comments
Post a Comment