无需正则表达式(RegEx)或自定义代码,如何去除字符串首尾子串?
不使用正则或自定义代码去除字符串首尾子串/字符的方案
能不能不用正则表达式(RegEx)或者自定义代码,去除字符串的首尾字符及子串?比如要移除开头的https://和结尾的/。虽然用自定义代码或正则能解决,但团队里很多人对这类修改存疑,也不想花时间学正则来验证,希望重构后切换和验证操作简单便捷,有没有现成的包或内置方法能处理首尾的查找替换?
原示例代码
@Value("${elsewhere.host.url:https://url.or.uri.full.or.partial}") String urlOrUri; // ... String scheme = "https://"; // Example 1: if (urlOrUri.startsWith(scheme)) urlOrUri.replaceFirst(scheme,""); if (urlOrUri.startsWith("/")) urlOrUri.replaceFirst("/",""); if (urlOrUri.endsWith("/")) urlOrUri.replaceLast("/",""); // Example 2: urlOrUri.replaceFirst("^https://+", ""); urlOrUri.replaceFirst("^/+", ""); urlOrUri.replaceFirst("/+$", "");
可行方案
1. Java 内置方法实现(无依赖)
利用startsWith()、endsWith()判断前缀/后缀,结合substring()截取字符串,逻辑直观,无需正则:
@Value("${elsewhere.host.url:https://url.or.uri.full.or.partial}") String urlOrUri; // ... String scheme = "https://"; String processedUrl = urlOrUri; // 移除开头指定的scheme if (processedUrl.startsWith(scheme)) { processedUrl = processedUrl.substring(scheme.length()); } // 移除开头所有连续的/ while (processedUrl.startsWith("/")) { processedUrl = processedUrl.substring(1); } // 移除结尾所有连续的/ while (processedUrl.endsWith("/")) { processedUrl = processedUrl.substring(0, processedUrl.length() - 1); }
这种方式逻辑清晰,团队成员无需了解正则就能快速验证每一步的作用,避免正则带来的理解成本。
2. 第三方工具包简化代码
如果可以引入第三方依赖,Apache Commons Lang的StringUtils类提供了专门的首尾处理方法,完全无需正则,代码更简洁:
首先引入依赖(Maven为例):
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.14.0</version> </dependency>
然后使用对应的方法处理:
import org.apache.commons.lang3.StringUtils; // ... String processedUrl = urlOrUri; // 移除开头的指定子串(仅匹配一次开头) processedUrl = StringUtils.removeStart(processedUrl, "https://"); // 移除开头所有的/字符 processedUrl = StringUtils.stripStart(processedUrl, "/"); // 移除结尾所有的/字符 processedUrl = StringUtils.stripEnd(processedUrl, "/");
StringUtils的这些方法自带安全处理:如果字符串不匹配目标前缀/后缀,会直接返回原字符串,无需额外写判断逻辑,可读性和维护性都很强。
内容的提问来源于stack exchange,提问作者Zach
相关产品推荐
相关产品推荐

