如何提取首尾相同字符串间的子串?Java实现方案咨询
解决方案:提取首尾相同字符串间的子串
原代码问题分析
你的代码返回"is"是因为两个核心问题:
indexOf("is")匹配到的是原字符串中第一个出现的"is"(即"this"里的最后两个字符,索引2),而非你期望的独立"is";substring(startIndex, endIndex)会包含起始位置的"is",且结束位置是第二个"is"的起始索引,导致截取内容不符合预期。
方法1:纯Java8原生实现
通过定位第一个匹配串的结束位置和最后一个匹配串的起始位置,截取中间内容,同时处理边界情况:
String originalString = "this is an example to extract sentence between is"; String startEndString = "is"; // 定位第一个匹配串的起始位置 int firstMatchPos = originalString.indexOf(startEndString); if (firstMatchPos == -1) { System.out.println("未找到匹配的起始字符串"); return; } // 跳过起始字符串,从其结束位置开始截取 int startIndex = firstMatchPos + startEndString.length(); // 定位最后一个匹配串的起始位置 int lastMatchPos = originalString.lastIndexOf(startEndString); if (lastMatchPos <= firstMatchPos) { System.out.println("未找到有效结束字符串"); return; } // 截取中间内容并去除前后空格 String result = originalString.substring(startIndex, lastMatchPos).trim(); System.out.println(result); // 输出:an example to extract sentence between
方法2:正则表达式实现(Java8支持)
利用正则匹配首尾串之间的内容,自动处理特殊字符转义:
String originalString = "this is an example to extract sentence between is"; String startEndString = "is"; // 转义正则特殊字符,避免匹配异常 String regex = Pattern.quote(startEndString) + "(.*?)" + Pattern.quote(startEndString); Matcher matcher = Pattern.compile(regex).matcher(originalString); String result = ""; // 提取第一个匹配的中间内容 if (matcher.find()) { result = matcher.group(1).trim(); } System.out.println(result); // 输出:an example to extract sentence between
方法3:Apache Commons Lang StringUtils 实现
结合lastIndexOf和substring方法,简化代码:
String originalString = "this is an example to extract sentence between is"; String startEndString = "is"; int startIndex = originalString.indexOf(startEndString) + startEndString.length(); int endIndex = StringUtils.lastIndexOf(originalString, startEndString); if (startIndex < endIndex) { String result = StringUtils.substring(originalString, startIndex, endIndex).trim(); System.out.println(result); }
内容的提问来源于stack exchange,提问作者rakesh_parashar
相关产品推荐
相关产品推荐

