I am trying to write a generic method that will search a file for a given string and replace it with another string. I am using java regex for the same
patternMatcher = Pattern.compile(searchString);
while ((line = readLine()) != null) {
Matcher regexMatcher = patternMatcher.matcher(line);
if (regexMatcher.lookingAt()) {
line = regexMatcher.replaceAll(replaceString);
..so on
This logic works as long as the search string is in the beginning of each line in the file. otherwise the pattern matching does not occur. Can anyone please suggest a solution?
for eg. My search String is "This" and Replace string is "That"
Input file contains: This is not This funny
Output: That is not That funny
But when
Input file contains: 007 This is not This funny
Output: 007 This is not This funny
Shouldn't it be...?
patternMatcher = Pattern.compile(searchString);
while ((line = readLine()) != null) {
Matcher regexMatcher = patternMatcher.matcher(line);
while (regexMatcher.find()) {
line = regexMatcher.replaceAll(replaceString);
Take into account that the quatifier may affect the results, perhapaps the search string should be "(this)+" or "(this)+?".
If you're searching for a constant string and not for a pattern, there's a number of reasons why you shouldn't use regex:
Use String.indexOf
and/or String.replace
instead.
while ((line = readLine()) != null)
if (line.indexOf(searchString) != -1 )
line.replace(searchString, replaceString);
I'm not familiar with Java, but as per the docs, lookingAt
looks at the beginning of the string. I would just skip looking for the match and blindly run replaceAll
regardless of whether there is a match; it will replace nothing if there is no match.
If for some reason you need to look for a match before attempting to replace (which is wasteful), the correct function is find
. See http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Matcher.html
如果内存不是问题,则可以将整个文件读取为String,并在String API中使用public String replaceAll(String regex, String replacement)
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.