Java字符串替换:将URL中的webp替换为jpg、.webp替换为.jpeg
Java实现URL中指定
webp目录与后缀的替换 原URL:
https://example.com/uploads/images/quotes/hi/webp/dard-status-shayari-68854.webp
需求:将路径中的webp目录替换为jpg,同时将文件后缀.webp替换为.jpeg,最终得到:
https://example.com/uploads/images/quotes/hi/jpg/dard-status-shayari-68854.jpeg
解决方案1:分步精确替换
针对两个不同的替换点分两次处理,避免全局替换的冲突:
public class UrlReplaceDemo { public static void main(String[] args) { String downloadUrl = "https://example.com/uploads/images/quotes/hi/webp/dard-status-shayari-68854.webp"; // 替换路径中的/webp/目录为/jpg/ String tempUrl = downloadUrl.replace("/webp/", "/jpg/"); // 替换结尾的.webp后缀为.jpeg String finalUrl = tempUrl.replace(".webp", ".jpeg"); System.out.println(finalUrl); } }
解决方案2:正则匹配(适配更复杂场景)
如果需要更严谨的匹配(比如目录位置不固定、避免误匹配其他含webp的字符串),可以用正则分别定位两个目标:
import java.util.regex.Pattern; public class UrlRegexReplaceDemo { public static void main(String[] args) { String downloadUrl = "https://example.com/uploads/images/quotes/hi/webp/dard-status-shayari-68854.webp"; // 匹配路径中的/webp/目录,替换为/jpg/ String dirReplaced = Pattern.compile("/webp/").matcher(downloadUrl).replaceAll("/jpg/"); // 匹配结尾的.webp后缀,替换为.jpeg String finalUrl = Pattern.compile("\\.webp$").matcher(dirReplaced).replaceAll(".jpeg"); System.out.println(finalUrl); } }
关于之前方案失效的原因
你之前尝试的精确单词替换方案,可能是全局匹配了webp字符串,这样会把后缀里的webp也替换成jpg,导致结果不符合预期。而分步或分位置的精确匹配,能区分开目录和后缀两个不同的替换目标。
内容的提问来源于stack exchange,提问作者Manisha
相关产品推荐
相关产品推荐

