Java实现移除字符串末尾以_v开头的后缀
Java中移除字符串末尾以_v开头的版本后缀
方法一:正则表达式(推荐)
直接用String.replaceAll()方法配合正则表达式,精准匹配末尾的_v(不区分大小写)加数字的后缀,替换为空字符串即可。
正则表达式说明:
(?i):开启不区分大小写模式,同时兼容_V和_v格式_v:匹配下划线加字母v(大小写都生效)\\d+:匹配一个或多个连续数字$:限定匹配必须出现在字符串末尾
代码示例:
String input = "Abs_es_ten_V1"; String result = input.replaceAll("(?i)_v\\d+$", ""); System.out.println(result); // 输出:Abs_es_ten // 其他测试用例 input = "test_v23"; result = input.replaceAll("(?i)_v\\d+$", ""); System.out.println(result); // 输出:test input = "demo_v6"; result = input.replaceAll("(?i)_v\\d+$", ""); System.out.println(result); // 输出:demo
方法二:手动定位截取(无正则方案)
如果不想依赖正则,可以手动查找最后一个下划线的位置,再判断后续字符是否符合后缀规则,符合则截取前面的部分。
代码示例:
public static String removeVersionSuffix(String input) { int lastUnderscoreIndex = input.lastIndexOf('_'); if (lastUnderscoreIndex == -1) { return input; // 没有下划线,直接返回原字符串 } // 检查下划线后的子串是否是v/V开头+数字的格式 String suffix = input.substring(lastUnderscoreIndex + 1); if (suffix.matches("(?i)v\\d+")) { return input.substring(0, lastUnderscoreIndex); } return input; // 不符合后缀规则,返回原字符串 } // 测试 System.out.println(removeVersionSuffix("Abs_es_ten_V1")); // Abs_es_ten System.out.println(removeVersionSuffix("hello_world")); // hello_world(无符合后缀,返回原串)
内容的提问来源于stack exchange,提问作者Kesavan Balakrishnan
相关产品推荐
相关产品推荐

