简体   繁体   English

如何计算Java中文本文件中的括号和花括号?

[英]How do I count parenthesis and curly brackets in a text file in Java?

I am trying to count the number of sub-strings the program finds within a text document. 我试图计算程序在文本文档中找到的子字符串的数量。 Text Document: 文字文件:

# Data Value 0:
dataValue(0) {
  x: -3
  y: +9
  width: 68
  height: 25
}

In my program, I am trying to print the number of times that 'dataValue(' occurs. I am having trouble with the parenthesis. From what I found while searching for a solution, I have to escape the parenthesis. Is this correct? However, I found that when I do so, the program interprets it as 'dataValue\\(' instead of 'dataValue('. As a result, no matches are found. Can I get around this? If so, any help would be appreciated. 在我的程序中,我试图打印'dataValue('发生的次数。我的括号有问题。从我在搜索解决方案时发现的,我必须逃避括号。这是正确的吗?但是,我发现当我这样做时,程序将其解释为'dataValue \\('而不是'dataValue('。因此,没有找到匹配。我可以解决这个问题吗?如果是这样,任何帮助都将受到赞赏。

Main Method: 主要方法:

static String fileContent = "";

public static void main(String args[]) {

    fileContent = getFileContent("/Users/Rane/Desktop/search.txt");
    System.out.println(countSubstring(fileContent, "dataValue\\("));

}

getFileContent() Method: 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() Method: 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;

}

Console Output: 控制台输出:

dataValue\(
0

Thanks in advance! 提前致谢!

For the indexOf , you do not need to escape the ( . The indexOf takes in a string as parameter and not a regular expression unlike some other methods. 对于indexOf ,您不需要转义( indexOf接受字符串作为参数而不是其他方法的正则表达式。

Another note, you would need to change this if you just want to count things: 另外需要注意的是,如果你只是想数一下,你需要改变它:

while(search.indexOf(substring) > -1) {
    search = search.replaceFirst(substring, "");
    occurrences ++;
}

To: 至:

int index = -1;

while((index = search.indexOf(substring, ++index)) > -1) 
    occurances++;

The indexOf yields the location of the provided substring. indexOf产生提供的子字符串的位置。 We are using an overloaded version which also takes from where to start matching. 我们正在使用一个重载版本,它也需要从哪里开始匹配。 We need this so as to avoid keep finding the same element, thus making it an infinite loop. 我们需要这样做以避免继续找到相同的元素,从而使它成为无限循环。

That is because you're mixing the use of the search string: 那是因为你混合使用搜索字符串:

  • indexOf() takes a plain search string indexOf()采用普通搜索字符串
  • replaceFirst() takes a regular expression replaceFirst()采用正则表达式

If you just want to supply a plain string, you can quote the string for use as a regular expression using Pattern.quote() . 如果您只想提供普通字符串,可以使用Pattern.quote()引用字符串以用作正则表达式。

Better yet, don't waste time on replacing the search string, just keep searching, using either indexOf() for simple search strings, or find() for regular expressions: 更好的是,不要浪费时间更换搜索字符串,只需继续搜索,使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM