This is usually the case: Search the document for a regular string, and then count or replace it. The two classes of pattern and Matcher under the Java.util.regex package provide the ability to match queries and even replace them with regular expressions. So let's just raise a chestnut, then:
Chestnut 1: Find a string in the file that img_ the number. png format and add the path in front:/test/img/
package test;import java.io.file;import Java.util.regex.matcher;import Java.util.regex.pattern;import Org.apache.commons.io.fileutils;public class Patterntest {private static final String conststring = "<a></a>";p ublic static void Main (string[] args) throws Exception {File File = new file ("C:\\users\\admin\\desktop\\test.txt"); Fileutils.writestringtofile (file, conststring); String str = fileutils.readfiletostring (file, "UTF-8"); StringBuffer StringBuffer = new StringBuffer ();//The regular expression that sets the pattern is pattern P = pattern.compile ("Img_[0-9]+\\u002png");// Match Matcher m = P.matcher (str) by rule, while (M.find ()) {//Adds the matched to and replaced string and the preceding string to StringBuffer m.appendreplacement ( StringBuffer, "/test/img/" +m.group ()); System.out.println (Stringbuffer.tostring ()); System.out.println ();} Adds a string after the matched string to the StringBuffer m.appendtail (StringBuffer); Fileutils.writestringtofile (file, stringbuffer.tostring (), "UTF-8");}}
In fact, there is an easy way to do this, and here's an extension:
Package Test;import Java.io.file;import Java.util.regex.matcher;import java.util.regex.pattern;import Org.apache.commons.io.fileutils;public class Patterntest { private static final String conststring = "<a>< IMG src= ' img_01.png '/></a> "; public static void Main (string[] args) throws Exception { file File = new file ("C:\\users\\jd07201\\desktop\\test.txt "); Fileutils.writestringtofile (file, conststring); String str = fileutils.readfiletostring (file, "UTF-8"); str = str.replace ("Img_", "/test/img/" + "Img_"); Fileutils.writestringtofile (file, str, "UTF-8");} }
The premise of this method is that the match condition must only be mapped to the target string, which means that the match condition "img_" must be equivalent to "img_[0-9]+\\u002png", otherwise it is possible to replace the string that does not meet the criteria.
Java Regular Expression Pattern&matcher