首页 > 解决方案 > 使用正则表达式从另一个字符串中提取一部分字符串

问题描述

假设我有一个字符串,如下所示:

 s = '23092020_indent.xlsx'

我只想indent从上面的字符串中提取。现在有很多方法:

#Via re.split() operation
s_f = re.split('_ |. ',s) <---This is returning 's' ONLY. Not the desired output

#Via re.findall() operation
s_f = re.findall(r'[^A-Za-z]',s,re.I) 
s_f
['i','n','d','e','n','t','x','l','s','x']  
s_f = ''.join(s_f) <----This is returning 'indentxlsx'. Not the desired output

我错过了什么吗?还是我需要使用regex

PS在整个部分中s只有'.'分隔符将是恒定的。休息所有分隔符都可以更改。

标签: python

解决方案


使用os.path.splitext然后str.split

import os
name, ext = os.path.splitext(s)
name.split("_")[1] # If the position is always fixed

输出:

"indent"

推荐阅读