开发者

Split a string on whitespace, numbers, and operators with regex

I was wondering 开发者_StackOverflow社区if it was possible to split a string on whitespace, and avoid all numbers, whitespace and operators such as + and -

This is what I have, but I believe it is incorrect

  String [] temp = expression.split("[ \\+ -][0-9] ");

Suppose I have an expression

x+y+3+5+z

I want to get rid of everything else and only put x, y, and z into the array


I think you mean this:

String[] temp = expression.split("[\\s0-9+-]+");

This splits on whitespace, 0 to 9, + and -. Note that the characters appear in a single character class, not multiple separate character classes. Also the - doesn't need escaping here because it is at the end of the character class.


I think this is what you're after:

String[] tmp = expression.split("[^a-zA-Z]+");

which should treat the separator as being anything that isn't a sequence of letters.

Test Run

public class foo {
    static public void main(String[] args) {
        String[] res = args[0].split("[^a-zA-Z]+");
        for (String r: res) {
            System.out.println(r);
        }
    }
}

% javac foo.java
% java foo x+y+3+5+z
x
y
z
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜