Problem parsing regular expressions of a jTextArea

Asked

Viewed 52 times

0

I am trying to analyze a text typed in a jTextArea, in the form of an algorithm in English. Initially I must recognize the main method, which is characterized by "beginning" and "end". The way I’m doing (code below), my logic only works if everything is on the same line, no matter what is between the two words for example:

start .... end asdf

I need that when typing in jTextArea, the logic works even if the line is broken by an Enter, for example:

beginning
....
asdf
end

What can I do to make it work?

      String a = jTextArea1.getText();

    //----- METODO PRINCIPAL ----
    boolean valInicio = a.matches("^inicio.*");
    boolean valFim = a.matches(".*fim$");
    if (valInicio) {
        jTextArea2.setText(jTextArea2.getText() + "\nEcontrou o inicio do programa!");
        if (valFim) {
            jTextArea2.setText(jTextArea2.getText() + "\nEcontrou o fim do programa!");
        }
    }
  • One way would be to replace all the line breaks before giving matche: a.replace("\n", ":quebra:"). After checking you could return the text to normal: a.replace(":quebra:", "\n")

  • Later I will need my code to analyze more things within this "code" typed in jTextArea, such as relational operators, arithmetic, and other items, regardless of how many lines the code has. Using this way will it work for the next items of my work?

  • I believe so.

1 answer

1


The flags Pattern.DOTALL and Pattern.MULTILINE can help you.

String patternString = "[\\s\\S]*^inicio.*[\\s\\S]*fim$[\\s\\S]*";
Pattern pattern = Pattern.compile(patternString, Pattern.MULTILINE);
System.out.println(pattern.matcher(a).find());

In this way, any text that starts with inicio, end with fim and meet any of the criteria below will be found by regex:

  • Has line break(s) and/or space(s) before "start"
  • Has line break(s) and/or space(s) between "start" and "end"
  • Has line break(s) and/or space(s) after "end"
  • Gave it right, thank you Marcelo!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.