用regex-python检索字符串的子集

2024-04-29 14:54:41 发布

您现在位置:Python中文网/ 问答频道 /正文

p = "\home\gef\Documents\abc_this_word_dfg.gz.tar"

我正在寻找一种检索this_word的方法

base = os.path.basename(p)
base1 = base.replace("abc_","")
base1.replace("_dfg.gz.tar","")

这是可行的,但并不理想,因为我需要提前知道要删除哪些字符串。也许regex在这里合适


Tags: path方法homebaseostarthisreplace
2条回答

您没有给出太多信息,但是从所显示的内容来看,您不能在_字符上拆分吗

可能是这样的:

>>> p = os.path.join('home', 'gef', 'Documents', 'abc_this_word_dfg.gz.tar')
>>> p
'home/gef/Documents/abc_this_word_dfg.gz.tar'
>>> os.path.dirname(p)
'home/gef/Documents'
>>> os.path.basename(p)
'abc_this_word_dfg.gz.tar'
>>> '_'.join(
...     os.path.basename(p).split('_')[1:-1])
'this_word'

它按下划线拆分,然后丢弃第一部分和最后一部分,最后用下划线将其他部分连接在一起(如果this_word没有下划线,则只剩下一个部分,将不进行连接)

你没有给出太多的信息,但是从所显示的内容来看,你不能仅仅使用字符串切片吗

可能是这样的:

>>> p = os.path.join('home', 'gef', 'Documents', 'abc_this_word_dfg.gz.tar')
>>> p
'home/gef/Documents/abc_this_word_dfg.gz.tar'
>>> os.path.dirname(p)
'home/gef/Documents'
>>> os.path.basename(p)
'abc_this_word_dfg.gz.tar'
>>> os.path.basename(p)[4:-11]
'this_word'

相关问题 更多 >