使用正则方式提取文本中间内容
获取文本中间(单次)
参数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("}", "\\}");
}
标签:zLen,java,String,text,replace,获取,文本,left From: https://www.cnblogs.com/Hello233/p/17233890.html