Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用不规则分隔符提取字符串的一部分_Python_Regex - Fatal编程技术网

在python中使用不规则分隔符提取字符串的一部分

在python中使用不规则分隔符提取字符串的一部分,python,regex,Python,Regex,我想提取文件名的最后一部分,该部分由常量前缀和“.csv”分隔 文件名可能如下所示: 常量\u前缀\ustrong>我的文件名.csv 或 常量前缀\ustrong>myfilename.csv 我想将粗体标记的值提取到变量中 请告知。使用str.split和os.path.splitext: >>> import os >>> prefix = 'constant_prefix' # if your prefix includes the trailing

我想提取文件名的最后一部分,该部分由常量前缀和“.csv”分隔

文件名可能如下所示:

常量\u前缀\ustrong>我的文件名.csv

常量前缀\ustrong>myfilename.csv

我想将粗体标记的值提取到变量中


请告知。

使用
str.split
os.path.splitext

>>> import os
>>> prefix = 'constant_prefix'

# if your prefix includes the trailing `_` then don't use `_` in `str.split`
# i.e just use this : `strs.split(prefix)[-1]`

>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'myfilename'

>>> strs = "constant_prefix_my file name.csv"
>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'my file name'

使用
str.split
os.path.splitext

>>> import os
>>> prefix = 'constant_prefix'

# if your prefix includes the trailing `_` then don't use `_` in `str.split`
# i.e just use this : `strs.split(prefix)[-1]`

>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'myfilename'

>>> strs = "constant_prefix_my file name.csv"
>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'my file name'
脚本:

import re

name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'

def get_name(string):
    return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]
演示:

输出:

my file name
myfilename
['my file name', 'myfilename']
或者您可以这样做:

names = [get_name(n) for n in [name1, name2]]
print names
输出:

my file name
myfilename
['my file name', 'myfilename']
脚本:

import re

name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'

def get_name(string):
    return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]
演示:

输出:

my file name
myfilename
['my file name', 'myfilename']
或者您可以这样做:

names = [get_name(n) for n in [name1, name2]]
print names
输出:

my file name
myfilename
['my file name', 'myfilename']

非常简单的正则表达式:
\uu(.*)\.csv$
@HamZa,它将从
无前缀文件名.csv
中捕获
文件名
,因此您必须添加前缀,就像我做的那样。@PeterVaro有道理…非常简单的正则表达式:
\u(.*)\.csv$
@HamZa,它将从
无前缀文件名.csv>中捕获
文件名
,所以你必须加上前缀,就像我做的那样。@PeterVaro有道理。。。