[java] Java String.split() Regex

I have a string:

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]

I've got this currently:

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?

This question is related to java regex string split

The answer is


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];

This should do it. Everything nicely stored in res.


Can you invert your regex so split by the non operation characters?

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

This obviously doesn't return the variables in the array. Maybe you can interleave two splits (one by the operators, one by the variables)


You could split on a word boundary with \b


    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);
        }
    }

Output : + - * / < > >= <= ==


You could also do something like:

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

It handles white spaces and words of variable length and produces the array:

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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows