Split Java string

I have problems with Java regular expressions. I have a line like this

a + 4 * log(3/abs(1 – x)) + sen(-b/4 + PI)

and I need to break it down in the following tokens:

{"a", "+", "4", "*", "log", "(3/abs(1 - x))", "+", "sen", "(-b/4 + PI)"}

Any idea?

I tried this regex php but for some reason it won't work in Java

[a-z]+(\((?>[^()]+|(?1))*\))|[a-z]+|\d+|\/|\-|\*|\+
+4
source share
2 answers

Match All Against Separation

Matching and splitting are two sides of the same coin. This is quite complicated because Java does not support recursion, and we have several nested parentheses. But this should do the trick:

Java

\(.*?\)(?![^(]*\))|[^\s(]+

See the demo .

To iterate over all matches:

Pattern regex = Pattern.compile("\\(.*?\\)(?![^(]*\\))|[^\\s(]+");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    // the match: regexMatcher.group()
} 

Explanation

  • \(.*?\)(?![^(]*\)) , . (simple(nesting)) , (this(kind)of(nesting)) (. PHP)
  • | ...
  • [^\s(]+ , par

PHP-

PHP ( Java (this(kind)of(nesting)):

(\((?:[^()]++|(?1))*\))|[^\s(]+
+4

java spli, ,

 import java.util.ArrayList;


public class Test2 {
    public static void main(String args[]) {

        System.out.println(splitExp("a + 4 * log(3/abs(1 – x)) + sen(-b/4 + PI)"));
    }

    private static ArrayList<String> splitExp(String exp) {

        StringBuilder chString = new StringBuilder();
        ArrayList<String> arrL = new ArrayList<String>();

        for (int i = 0 ; i < exp.length() ; i++ ) {

            char ch = exp.charAt(i);

            if(ch == ' ')
                continue;

            if(( ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
                chString = chString.append(String.valueOf(ch));
            }
            else {
                if (chString.length() > 0) {
                    arrL.add(chString.toString());
                    chString = new StringBuilder();
                }
                arrL.add(String.valueOf(ch));
            }
        }
        return arrL;
    }
}
+1

Source: https://habr.com/ru/post/1546929/


All Articles