简体   繁体   中英

Regex to split numeric expressions

I need to split numeric expressions. The basics are easy, but... I've tried

public static void main(String[] args) {
    String [] a = {"1+1", "1-1", "22*43", "25/17", "-3 * -3"};
    String [] z;
    for(int i = 0; i < a.length; i++){
        z = a[i].split("[\\D]");
        System.out.println(i + ":  " + a[i] + "  |" + z[0] + "|  " + "|" + z[1] + "|");
    }
}

I get:

0:  1+1  |1|  |1|
1:  1-1  |1|  |1|
2:  22*43  |22|  |43|
3:  25/17  |25|  |17|
4:  -3 * -3  ||  |3|

The problem is line 4: which should be:

4:  -3 * -3  |-3|  |-3|

Is it possible to enhance the regex \\\\D to achieve this?

Here the problem is that \\D also captures - sign.

One solution is to handle - sign at the beginning of an expression and right after an operator as two special cases.

A more elegant solution will be to implement a grammar. See http://lukaszwrobel.pl/blog/math-parser-part-2-grammar .

只要您不连接这些表达式,该代码就可以满足您的需要:

"(?<=\\d)\\s*\\D\\s*(?=\\d|-)"

Try this:

    public static void main(String[] args) {
        String[] a = {"1+1", "1-1", "22*43", "25/17", "-3 * -3"};
        for (int i = 0; i < a.length; i++) {
            String s = a[i].replaceAll(" ", "");
            String z2 = s.replaceAll("(.*[\\d])([\\D])(.*)", "|$1|"+"|$3|");
            System.out.println(z2);
        }
    }

If you want to use recursion to support expressions of all lengths, do as below:

static Pattern p; //declare this member in the class

public static void main(String[] args) {
    p = Pattern.compile("(.*[\\d])([\\D])(.*)");
    String[] a = { "1+1", "1-1", "22*43", "25/17", "-3 * -3 - -4" };
    for (int i = 0; i < a.length; i++) {
        String s = a[i].replaceAll(" ", "");
        split(s);
        System.out.println("\n");
    }
}

static void split(String s) {
    Matcher m = p.matcher(s);
    if (!m.matches())
        return;
    else {
        for (int i = 1; i <= 3; i += 2) {
            if (m.group(i).length() < 3) {
                System.out.print(" |" + m.group(i) + "| ");
            } else
                split(m.group(i));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM