Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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 3.x 查找基于正则表达式的字符匹配_Python 3.x_Regex - Fatal编程技术网

Python 3.x 查找基于正则表达式的字符匹配

Python 3.x 查找基于正则表达式的字符匹配,python-3.x,regex,Python 3.x,Regex,我有一个字符串列表,如下所示: a=['bukt/id=gdhf/year=989/month=98/day=12/hgjhg.csv','bukt/id=76fhfh/year=989/month=08/day=128/hkngjhg.csv'] ID是唯一的。我想有一个输出列表,类似这样 output_list = ['bukt/id=gdhf/','bukt/id=76fhfh/'] 所以基本上需要一个正则表达式来匹配任何id,并从字符串中删除该部分的其余部分 考虑到输入列表的长度超过

我有一个字符串列表,如下所示:

a=['bukt/id=gdhf/year=989/month=98/day=12/hgjhg.csv','bukt/id=76fhfh/year=989/month=08/day=128/hkngjhg.csv']
ID是唯一的。我想有一个输出列表,类似这样

output_list = ['bukt/id=gdhf/','bukt/id=76fhfh/']
所以基本上需要一个正则表达式来匹配任何id,并从字符串中删除该部分的其余部分

考虑到输入列表的长度超过100K,我如何以最有效的方式做到这一点

import re

rgx = r'(bukt/id=[a-zA-Z0-9]+/).+'
re.search(rgx, string).group(1)

结果将在第1组。这将捕获“bukt/id=”,后跟任何字母数字字符,然后是斜杠,并丢弃其余字符。

不需要正则表达式,您只需
/
上拆分
字符串,丢弃第二个
/
之后的所有内容,然后
再次使用
/
连接

a=['bukt/id=gdhf/year=989/month=98/day=12/hgjhg.csv','bukt/id=76fhfh/year=989/month=08/day=128/hkngjhg.csv']

out = ['/'.join(u.split('/')[:2]) for u in a]
print(out)
输出:

['bukt/id=gdhf', 'bukt/id=76fhfh']
['bukt/id=gdhf/', 'bukt/id=76fhfh/']
如果要使用尾随的
/
,只需在拆分数组的末尾添加一个空字符串:

out = ['/'.join(u.split('/')[:2] + ['']) for u in a]
输出:

['bukt/id=gdhf', 'bukt/id=76fhfh']
['bukt/id=gdhf/', 'bukt/id=76fhfh/']

格式为
bukt/id=xxx/…
的所有字符串是否正确?@Nick Yes,正确。仅更改年、月、日值