Java String.split()正则表达式 [英] Java String.split() Regex
本文介绍了Java String.split()正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串:
String str = "a + b - c * d / e < f > g >= h <= i == j";
我想在所有运算符上拆分字符串,但在数组中包含运算符,所以结果数组如下所示:
I want to split the string on all of the operators, but include the operators in the array, so the resulting array looks like:
[a , +, b , -, c , *, d , /, e , <, f , >, g , >=, h , <=, i , ==, j]
我目前有这个:
public static void main(String[] args) {
String str = "a + b - c * d / e < f > g >= h <= i == j";
String reg = "((?<=[<=|>=|==|\\+|\\*|\\-|<|>|/|=])|(?=[<=|>=|==|\\+|\\*|\\-|<|>|/|=]))";
String[] res = str.split(reg);
System.out.println(Arrays.toString(res));
}
这非常接近,它给出了:
This is pretty close, it gives:
[a , +, b , -, c , *, d , /, e , <, f , >, g , >, =, h , <, =, i , =, =, j]
我能做些什么吗为了使多个字符操作符出现在数组中,就像我想要的那样?
Is there something I can do to this to make the multiple character operators appear in the array like I want them to?
作为次要问题并不是那么重要,有没有办法在正则表达式中修剪字母周围的空白?
And as a secondary question that isn't nearly as important, is there a way in the regex to trim the whitespace off from around the letters?
推荐答案
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];
这应该这样做。一切都很好地存储在 res
。
This should do it. Everything nicely stored in res
.
这篇关于Java String.split()正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文