2024-09-29 23:24:15 发布
网友
表达式示例:
"abcddomain_rgz.png" "djhajhdomain_rgb1.png"
要将上述表达式中的domain*.png替换为"domain.json"
domain*.png
"domain.json"
答复:
"abcddomain.json" "djhajhdomain.json"
改用python正则表达式(re package):
re package
re.sub(r'domain.*\.png$', r"domain.json", 'djhajhdomain_rgb1.png')
这是注释部分提到的正则表达式的典型例子。由于在domain之后直到.png之前都不知道要替换的字符串的确切长度,因此需要使用正则表达式来执行替换
domain
.png
Python为您提供了^{}模块,您可以使用它的^{}函数执行替换:
import re string = "djhajhdomain_rgb1.png" result = re.sub("domain(.*).png", "domain.json", string) print(result)
这将返回:
djhajhdomain.json
你最好的选择是正则表达式
x = "djhajhdomain_rgb1.png" y = "djhajhdomain.json" import re pattern = re.compile(r'\w+domain') ext = '.json' match = re.match(pattern, x).group(0) result = match+ext assert result == y
改用python正则表达式(
re package
):re.sub(r'domain.*\.png$', r"domain.json", 'djhajhdomain_rgb1.png')
这是注释部分提到的正则表达式的典型例子。由于在
domain
之后直到.png
之前都不知道要替换的字符串的确切长度,因此需要使用正则表达式来执行替换Python为您提供了^{} 模块,您可以使用它的^{} 函数执行替换:
这将返回:
你最好的选择是正则表达式
相关问题 更多 >
编程相关推荐