Search code examples
javabnf

Extract strings outside square brackets


If I have a BNF code like this

[A] ::= [A]B | C | [D]
[D] ::= C[D] | C

how can I extract letters that are not inside square brackets. I have tried this

for(int i=0;i<lineNumber;i++)
    {
       String Data[]=data[i].split("::=");
       Nonter.add(Data[0]);
       ter.add(Data[1]);
       NterSay++;

    }

   String[] splitted = ter.get(0).split("\\[|\\]|\\|");
   for (String split: splitted) {      
System.out.println(split);

}

But it prints all the letters.


Solution

  • Try this:

        String[] data = new String[]{"[A] ::= [A]B | C | [D]", "[D] ::= C[D] | C"};
        List<String> nonter = new ArrayList<>();
        List<String> ter = new ArrayList<>();
    
        for (String aData : data) {
            String Data[] = aData.split("::=");
            nonter.add(Data[0]);
            ter.add(Data[1]);
        }
    
        String replaced = ter.get(0).replaceAll("\\[\\w]|\\s|\\|", "");
    
        for (char ch : replaced.toCharArray()) {
            System.out.println(ch);
        }