java文本获取中间内容
使用正则方式提取文本中间内容
获取文本中间(单次)
参数1:文本
参数2:文本前
参数3:文本后
返回一个String
public static String getSubString(String text, String left, String right) {
String result = "";
int zLen;
if (left == null || left.isEmpty()) {
zLen = 0;
} else {
zLen = text.indexOf(left);
if (zLen > -1) {
zLen += left.length();
} else {
zLen = 0;
}
}
int yLen = text.indexOf(right, zLen);
if (yLen < 0 || right == null || right.isEmpty()) {
yLen = text.length();
}
result = text.substring(zLen, yLen);
return result;
}
批量获取文本中间
参数1:文本
参数2:文本前
参数3:文本后
返回一个String列表
// 批量获取中间文本
public static List<String> GetSubTextList(String sourceText,String frontIdentificationText,
String subsequentIdentificationText) {
ArrayList<String> list = new ArrayList<>();
Pattern pattern = Pattern.compile(escapeMetacharacter(frontIdentificationText) + "([\\s\\S]*?)" +
escapeMetacharacter(subsequentIdentificationText), Pattern.DOTALL);
Matcher m = pattern.matcher(sourceText);
while (m.find()) {
String group = m.group(1);
list.add(group);
}
return list;
}
// 正则替换
public static String escapeMetacharacter(String text) {
return text.replace("?","\\?").replace("*", "\\*").replace("+", "\\+")
.replace("[", "\\[").replace("]", "\\]").replace("(", "\\(")
.replace(")", "\\)").replace("{", "\\{").replace("}", "\\}");
}
本文作者:Hello
本文链接:https://www.cnblogs.com/Hello233/p/17233890.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步