Java String.split()正则表达式

我有一个字符串:

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

我想在所有运算符上拆分字符串,但在数组中包含运算符,因此生成的数组如下所示:

 [a , +, b , -, c , *, d , /, e , , g , >=, h , <=, i , ==, j] 

我现在有这个:

 public static void main(String[] args) { String str = "a + b - c * d / e  g >= h <= i == j"; String reg = "((?<=[=|==|\\+|\\*|\\-||/|=])|(?=[=|==|\\+|\\*|\\-||/|=]))"; String[] res = str.split(reg); System.out.println(Arrays.toString(res)); } 

这非常接近,它给出了:

 [a , +, b , -, c , *, d , /, e , , g , >, =, h , <, =, i , =, =, j] 

有什么我可以做到这一点,使多个字符操作符出现在数组中,就像我想要的那样?

作为一个不太重要的次要问题,正则表达式是否有办法从字母周围修剪空白?

 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

 str.split (" ") res27: Array[java.lang.String] = Array(a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j) 
  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); } } 

输出:+ - * / <>>> = <= ==

您可以使用\ b拆分单词边界

你可以将你的正则表达式反转为非操作字符吗?

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

这显然不会返回数组中的变量。 也许你可以交错两个分裂(一个由运算符,一个由变量)

你也可以这样做:

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

它处理空格和可变长度的单词并生成数组:

 [a, +, b, -, c, *, d, /, e, <, f, >, g, >=, h, <=, i, ==, j]