Java String.split() Regex

后端 未结 6 570
南笙
南笙 2020-11-27 16:23

I have a string:

String str = \"a + b - c * d / e < f > g >= h <= i == j\";

I want to split the string on all of the operators

相关标签:
6条回答
  • 2020-11-27 16:47

    You could split on a word boundary with \b

    0 讨论(0)
  • 2020-11-27 16:53
    String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
    String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
    String[] res = new String[ops.length+notops.length-1];
    for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];
    

    This should do it. Everything nicely stored in res.

    0 讨论(0)
  • 2020-11-27 16:57
    str.split (" ") 
    res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j)
    
    0 讨论(0)
  • 2020-11-27 16:59
        String str = "a + b - c * d / e < f > g >= h <= i == j";
        String reg = "\\s*[a-zA-Z]+";
    
        String[] res = str.split(reg);
        for (String out : res) {
            if (!"".equals(out)) {
                System.out.print(out);
            }
        }
    

    Output : + - * / < > >= <= ==

    0 讨论(0)
  • 2020-11-27 17:01

    Can you invert your regex so split by the non operation characters?

    String ops[] = string.split("[a-z]")
    // ops == [+, -, *, /, <, >, >=, <=, == ]   
    

    This obviously doesn't return the variables in the array. Maybe you can interleave two splits (one by the operators, one by the variables)

    0 讨论(0)
  • 2020-11-27 17:01

    You could also do something like:

    String str = "a + b - c * d / e < f > g >= h <= i == j";
    String[] arr = str.split("(?<=\\G(\\w+(?!\\w+)|==|<=|>=|\\+|/|\\*|-|(<|>)(?!=)))\\s*");
    

    It handles white spaces and words of variable length and produces the array:

    [a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]
    
    0 讨论(0)
提交回复
热议问题