如何通过python的re模块删除最短匹配的模式?

时间:2017-08-17 15:13:07

标签: python bash

我正在将我的bash代码转换为python代码。

现在我想创建一个具有相同功能的功能 bash中的$ {variable#pattern};删除最短匹配模式,

例如,我希望delete_head(' _usr_home_you_file.ext.tar.oz',r' _。* _')会产生' home_you_file.ext.tar.oz& #39;

我在下面创建了python函数,

import re

def delete_head(word,pattern):   
    re.sub('^{0}'.format(pattern), '', word)

然而,它会删除最长匹配的模式,如下所示。

word='_usr_home_you_file.ext.tar.oz'
delete_shortest_match=delete_head(word,r'_.*_')
print("word = {0}".format(word))
print("delete_shortest_match = {0}". format(delete_shortest_match))

输出:

word = _usr_home_you_file.ext.tar.oz
delete_shortest_match = file.ext.tar.oz  # I expected home_you_file.ext.tar.oz

如何创建一个删除最短匹配模式的函数,如上所述?

非常感谢。

2 个答案:

答案 0 :(得分:1)

bash前缀不是正则表达式,而是遵循glob模式匹配规则。正则表达式中的最短匹配可以用懒惰来实现(正则表达式默认是贪婪的)

r'_.*?_'

或者如果不支持或避免回溯

r'_[^_]*_'

答案 1 :(得分:1)

要获得最短匹配,请将?非贪婪限定符添加到*匹配零或更多量词:_.*?_

相关问题