python - 使用正则表达式从另一个字符串中提取一部分字符串
问题描述
假设我有一个字符串,如下所示:
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
只有'.'分隔符将是恒定的。休息所有分隔符都可以更改。
解决方案
使用os.path.splitext
然后str.split
:
import os
name, ext = os.path.splitext(s)
name.split("_")[1] # If the position is always fixed
输出:
"indent"
推荐阅读
- c++ - 我怎么知道谁拥有某个指针
- angular - 我们如何利用角度变化检测来提高性能?
- mysql - 在 CentOS 7.6 上无法远程连接 MariaDB 10.3
- django - Django项目的settings.py文件中的CELERY_TIMEZONE变量是什么意思?
- c++ - 自动存储和异常中没有无参数构造函数的类对象
- java - GSON - 如何始终在 json 中包含毫秒?
- c# - 返回新结构时如何防止复制?
- php - 如何创建 PHP SOAP 请求和响应
- django - Django-Admin TabularInline 在保存前修改内联项属性
- batch-file - 以常量“未找到路径”调用网络批处理