[英]How to replace/substitute part of the url with variable, using Python/Regex
I'm trying to replace part of the following URL with string from a variable: https://somedomain.eu/api/one/some/2018/05/data
How I can exclude some groups and use only one. 我正在尝试使用变量中的字符串替换以下URL的一部分:
https://somedomain.eu/api/one/some/2018/05/data
: https://somedomain.eu/api/one/some/2018/05/data
如何排除某些组并仅使用一个组。
This is what I did: 这就是我做的:
def change(var_data):
var = str(var_data) // for example: 11
url = 'https://somedomain.eu/api/one/some/2018/05/data'
url2 = re.sub(r'(\d\d)', var, url)
print(url2)
The print looks like this: https://somedomain.eu/api/one/some/1111/11/data
and it is wrong because I need to change only 05 to 11
, not 2018 to 1111
打印看起来像这样:
https://somedomain.eu/api/one/some/1111/11/data
: https://somedomain.eu/api/one/some/1111/11/data
,这是错误的,因为我只需要改变05 to 11
,而不是2018 to 1111
other version: 其他版本:
data_url_2 = re.sub(r'.+/(\d\d)/.+', month, data_url)
print(data_url_2)
print = '11' print = '11'
I was thinking of finding the way to make 3 groups and exclude first and the third one: 我正在考虑找到制作3组的方法,排除第一组和第三组:
data_url_2 = re.sub(r'(.+/\d\d\d\d)(\d\d)(/.+)', month, data_url)
Probably doesn't need regex but let's do it anyway. 可能不需要正则表达式,但无论如何我们都要这样做。
>>> import re
>>> url = 'https://somedomain.eu/api/one/some/2018/05/data'
>>> re.sub('/[\d]{2}/', '/11/', url)
'https://somedomain.eu/api/one/some/2018/11/data'
>>> re.sub('(?<=/)[\d]{2}(?=/)', '11', url)
'https://somedomain.eu/api/one/some/2018/11/data'
. 。
. 。
I was thinking of finding the way to make 3 groups and exclude first and the third one:
我正在考虑找到制作3组的方法,排除第一组和第三组:
What? 什么?
One way without regex 没有正则表达式的一种方法
def change(var_data):
var = str(var_data)
url = 'https://somedomain.eu/api/one/some/2018/05/data'
url1 = url.split('/')
url2 = '/'.join(url1[:-2] + [var] + [url1[-1]])
print(url2)
change('11')
#https://somedomain.eu/api/one/some/2018/11/data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.