Search code examples
javaregexstringlinefilereader

Reading contents inside brackets in Java?


I'm trying to read in some information from a file in Java, and the file contents are formatted like this:

InitialState [+A(B),+C(D)]
GoalState [-A(B),+C(D),-E(F)]

I'm trying to loop through the file and grab only the contents inside the brackets, so the arrays I create should look like this:

initial = ['+A(B)', '+C(D)']
goal = ['-A(B)', '+C(D)', '-E(F)']

Should I use a regex to do this? So far, I have

if (line.charAt(0) == 'I') {
  String[] initialStateString = (line.subString(line.subString(13, line.length() - 1)).split(","));
  for (String s: initialStateString) {
    initialState.add(s);
  }
}

if (line.charAt(0) == 'G') {
  String[] goalStateString = (line.subString(line.subString(11, line.length() - 1)).split(","));
    for (String s: goalStateString) {
      goalState.add(s)''
    }
}

This basically starts the index of the substring to be right after the bracket I believe, but I would like to use something that just takes the contents of the bracket as I believe that will be more robust. Thank you.


Solution

  • try this code :

    public static void main(String[] args) {
        String s = "InitialState [+A(B),+C(D)]";
        String s1 ="GoalState [-A(B),+C(D),-E(F)]";
    
        Pattern p = Pattern.compile("([+-]\\w\\(\\w\\))");
    
        Matcher m = p.matcher(s);
        while(m.find()){
            System.out.print(m.group(1)+"  ");
        }
    
        System.out.println();
    
        m = p.matcher(s1);
        while(m.find()){
            System.out.print(m.group(1)+"  ");
        }
    }
    

    output :

    +A(B)  +C(D)  
    -A(B)  +C(D)  -E(F)
    

    explanation for regex :

    [+-] : Match "+" or "-" character.
    \\w  : Match any word character.
    \\( : Match "(".
    \\) : Match ")"