引言
目前大多数人通常都是使用两种方式来对HTML文件进行处理的。一个是使用Jsoup,另一个就是使用正则表达式。
Jsoup是一个基于Java的HTML解析器,提供了省时省力的API,方便对文档进行各种处理。
不过正则表达式的处理方法就比较“蠢”了。这种方法就是简单地通过对文件内部字符串的处理,来达成修改的目的。
正则表达式
正则表达式(regular expression)是一种字符串的匹配模式,可以比较方便地检索字符串,找到与筛选规则相匹配的字段,并基于检索功能对字符串进行一系列的操作。
这方面需要学习的内容比较多,这里比较推荐去找一些实际的应用场景,然后与教程对着看,这样能更快更好地掌握正则表达式的实际应用能力。
代码展示
//按照首尾查找替换并计数【特殊格式】
public static int findAndCountByHeadTail(String filePath,String fixType){
int count = 0;
String temp = "";
StringBuffer tempBuf = new StringBuffer();
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 计算所有匹配的字符串的数量并替换
for (temp = null; (temp = br.readLine()) != null; temp = null) {
//匹配字符串
String leftStr = "text-decoration:" + fixType + ";\">";
String rightStr = "</span>";
//左匹配规则
Pattern leftPattern = Pattern.compile(leftStr);
Matcher leftMatcher = leftPattern.matcher(temp);
//右匹配规则
Pattern rightPattern = Pattern.compile(rightStr);
Matcher rightMatcher = rightPattern.matcher(temp);
int begin = 0;
List<String> foundKeys = new ArrayList<>();
//遍历匹配左右并提取中间字符串(包括左右匹配项)
while (leftMatcher.find(begin)){
rightMatcher.find(leftMatcher.start());
String presentKey = temp.substring(leftMatcher.start(),rightMatcher.end());
foundKeys.add(presentKey);
begin = rightMatcher.end();
count++;
}
//修改当前读取行
for (String foundKey : foundKeys){
temp = temp.replace(foundKey , foundKey.replace(leftStr,"\">"));
}
buf.append(temp);
buf.append(System.getProperty("line.separator"));
}
br.close();
FileOutputStream fos = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
解析
此处的特殊格式指的是:上划线、下划线、删除线等。同样的逻辑也可以用来处理其他的标签。
通过使用 Pattern
、 Matcher
进行前后字段的匹配,然后通过先遍历匹配到左串,然后匹配到右串,获取到左串在该行字符串的起始编号与右串在该字符串的结束编号。
然后,我们便可以很轻松地使用 String.substring
获取到包含左右标记串的子串,并在之后使用 String.replace
通过 for-each
来处理当前读取行的字符串。
所有修改最终都会返回到原文件。