简体   繁体   中英

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.

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:

    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:

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.

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. 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
  • replaceFirst() takes a regular expression

If you just want to supply a plain string, you can quote the string for use as a regular expression using 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:

// 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;

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.

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