我正在尝试计算程序在文本文档中找到的子字符串的数量。文字文件:
# Data Value 0:
dataValue(0) {
x: -3
y: +9
width: 68
height: 25
}
在我的程序中,我正在尝试打印'dataValue('发生的次数。我在使用括号时遇到问题。从我在搜索解决方案时发现的情况来看,我必须逃避括号。这是但是,我发现当我这样做时,程序将其解释为'dataValue \('而不是'dataValue('。结果,没有找到匹配。我可以解决这个问题吗?如果是这样,任何帮助都会不胜感激。
主要方法:
static String fileContent = "";
public static void main(String args[]) {
fileContent = getFileContent("/Users/Rane/Desktop/search.txt");
System.out.println(countSubstring(fileContent, "dataValue\\("));
}
getFileContent()方法:
public static String getFileContent(String filePath) {
File textFile = new File(filePath);
BufferedReader reader = null;
String content = "";
String currentLine = "";
if(textFile.exists()) {
try {
reader = new BufferedReader(new FileReader(textFile));
currentLine = reader.readLine();
while(currentLine != null) {
content = content + currentLine + "\n";;
currentLine = reader.readLine();
}
} catch(Exception ext) {
ext.printStackTrace();
} finally {
try {
reader.close();
} catch(Exception ext) {
ext.printStackTrace();
}
}
} else {
System.out.println("[WARNING]: Text file was not found at: " + filePath);
}
return content;
}
countSubstring()方法:
static int countSubstring(String search, String substring) {
int occurrences = 0;
System.out.println(substring);
search = search.toLowerCase();
substring = substring.toLowerCase();
while(search.indexOf(substring) > -1) {
search = search.replaceFirst(substring, "");
occurrences ++;
}
return occurrences;
}
控制台输出:
dataValue\(
0
提前致谢!
答案 0 :(得分:3)
对于indexOf
,您无需转义(
。与其他一些方法不同,indexOf
将字符串作为参数而不是正则表达式。
另一个注意事项,如果您只是想计算一些东西,则需要更改它:
while(search.indexOf(substring) > -1) {
search = search.replaceFirst(substring, "");
occurrences ++;
}
要:
int index = -1;
while((index = search.indexOf(substring, ++index)) > -1)
occurances++;
indexOf
生成所提供子字符串的位置。我们正在使用一个重载版本,它也需要从哪里开始匹配。我们需要这样做以避免继续找到相同的元素,从而使它成为无限循环。
答案 1 :(得分:1)
这是因为您正在混合使用搜索字符串:
indexOf()
采用普通搜索字符串replaceFirst()
采用正则表达式如果您只想提供普通字符串,可以使用Pattern.quote()
引用字符串以用作正则表达式。
更好的是,不要浪费时间更换搜索字符串,只需继续搜索,使用indexOf()
表示简单搜索字符串,或find()
表示正则表达式:
// Using indexOf() with a plain search string
int start = -1, count = 0;
while ((start = search.indexOf(substring, ++start)) != -1)
count++;
return count;
// Using find() with a regular expression search string
Matcher m = Pattern.compile(substring).matcher(search);
int count = 0;
while (m.find())
count++;
return count;