Java String.split() 正则表达式 [英] Java String.split() Regex

查看:50
本文介绍了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));
}

这非常接近,它给出:

[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆