Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

I was wondering 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

like image 238
Steffan Harris Avatar asked Oct 25 '22 00:10

Steffan Harris


2 Answers

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.

like image 136
Mark Byers Avatar answered Nov 03 '22 23:11

Mark Byers


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
like image 40
Alnitak Avatar answered Nov 03 '22 23:11

Alnitak