fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.ArrayList;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9.  
  10. /* Name of the class has to be "Main" only if the class is public. */
  11. class Ideone
  12. {
  13. public static void main (String[] args) throws java.lang.Exception
  14. {
  15. String source = "\\begin\\{theorem\\} Hello, World! \\end\\{theorem\\}";
  16. LatexTheoremProofExtractor extractor = new LatexTheoremProofExtractor(source);
  17. extractor.parse();
  18. ArrayList<String> theorems = extractor.getTheorems();
  19. System.out.println(theorems.get(0).trim());
  20. System.out.println("Hello, World!");
  21. }
  22. }
  23. class LatexTheoremProofExtractor {
  24.  
  25. // This is the LaTeX source that will be processed
  26. private String source = null;
  27.  
  28. // These are the list of theorems and proofs that are extracted, respectively
  29. private ArrayList<String> theorems = null;
  30. private ArrayList<String> proofs = null;
  31.  
  32. // These are the patterns to match theorems and proofs, respectively
  33. private static final Pattern THEOREM_REGEX = Pattern.compile(Pattern.quote("\\begin\\{theorem\\}") + "(.+?)" + Pattern.quote("\\end\\{theorem\\}"));
  34. private static final Pattern PROOF_REGEX = Pattern.compile(Pattern.quote("\\begin\\{proof\\}") + "(.+?)" + Pattern.quote("\\end\\{proof\\}"));
  35.  
  36. LatexTheoremProofExtractor(String source) {
  37. this.source = source;
  38. }
  39.  
  40. public void parse() {
  41. extractEntity("theorem");
  42. extractEntity("proof");
  43. }
  44.  
  45. private void extractTheorems() {
  46. if(theorems != null) {
  47. return;
  48. }
  49.  
  50. theorems = new ArrayList<String>();
  51.  
  52. final Matcher matcher = THEOREM_REGEX.matcher(source);
  53. while (matcher.find()) {
  54. theorems.add(new String(matcher.group(1)));
  55. }
  56. }
  57.  
  58. private void extractProofs() {
  59. if(proofs != null) {
  60. return;
  61. }
  62.  
  63. proofs = new ArrayList<String>();
  64.  
  65. final Matcher matcher = PROOF_REGEX.matcher(source);
  66. while (matcher.find()) {
  67. proofs.add(new String(matcher.group(1)));
  68. }
  69. }
  70.  
  71. private void extractEntity(final String entity) {
  72. if(entity.equals("theorem")) {
  73. extractTheorems();
  74. } else if(entity.equals("proof")) {
  75. extractProofs();
  76. } else {
  77. // TODO: Throw an exception or something
  78. }
  79. }
  80.  
  81. public ArrayList<String> getTheorems() {
  82. return theorems;
  83. }
  84.  
  85. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
Hello, World!
Hello, World!