fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.regex.Pattern;
  4. import java.util.regex.Matcher;
  5. import java.util.*;
  6. import java.lang.*;
  7. import java.io.*;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. ArrayList grammarRepo = new ArrayList();
  15. String item, grammar;
  16. String str = "( S ( NP-SBJ ( PRP I ) ) ( [email protected] ( VP ( VBP have ) ( NP ( DT a ) ( [email protected] ( NN savings ) ( NN account ) ) ) ) ( . . ) ) )";
  17. // cleanup double spaces:
  18. while (str.contains(" ")){
  19. str = str.replaceAll(" ", " ");
  20. }
  21. // find no parenthesis zones!
  22. Matcher m = Pattern.compile("\\([^\\(\\)]*\\)").matcher(str);
  23.  
  24. // loop until nothing left:
  25. while (m.find()) {
  26. item = m.group();
  27.  
  28. // make the grammar:
  29. grammar = item.substring(1, item.length()-1).trim().replaceFirst(" ", " -> ");
  30.  
  31. if (!grammarRepo.contains(grammar)) {
  32. grammarRepo.add(grammar);
  33. ps.print(grammar + "\n");
  34. }
  35.  
  36. str = str.replace(item, grammar.split(" -> ")[0]);
  37. m = Pattern.compile("\\([^\\(\\)]*\\)").matcher(str);
  38. }
  39. }
  40. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
PRP -> I
NP-SBJ -> PRP
VBP -> have
DT -> a
NN -> savings
NN -> account
[email protected] -> NN NN
NP -> DT [email protected]
VP -> VBP NP
. -> .
[email protected] -> VP .
S -> NP-SBJ [email protected]