[英]Search for any given string using JAVA REGEX
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
我正在使用Java正则表达式相同
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"
我的搜索字符串是“ This”,替换字符串是“ That”
Input file contains: This is not This funny
输入文件包含:
This is not This funny
Output: That is not That funny
输出:
That is not That funny
But when 但当
Input file contains: 007 This is not This funny
输入文件包含:
007 This is not This funny
Output: 007 This is not This funny
输出:
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)+?". 考虑到量化词可能会影响结果,可能搜索字符串应该是“(this)+”或“(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. 请改用
String.indexOf
和/或String.replace
。
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. 我对Java不熟悉,但是根据文档,
lookingAt
看起来在字符串的开头。 I would just skip looking for the match and blindly run replaceAll
regardless of whether there is a match; 我只是跳过寻找匹配项而盲目运行
replaceAll
而不管是否存在匹配项; 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
. 如果出于某种原因需要在尝试替换之前查找匹配项(这很浪费),则
find
正确的函数。 See http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Matcher.html 参见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)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.