user3466350
user3466350

Reputation: 11

Java string split using multiple operator delimiter

I need to divide a string into two parts at the first occurrence of any one of these operators:

||, &&, ==, !=, <, >, <=, >=, +, -, *, /, and %.

I think string.split() might be my best option, but I'm not certain. My problem is that I don't know exactly how to incorporate all of those symbols into a delimiter string for split(), or if that's even possible.

So, my question is, how would I create a delimiter string containing all of those operators? And if that's not possible, what would be the best alternative approach? Thanks!

Upvotes: 0

Views: 3514

Answers (2)

Dan King
Dan King

Reputation: 3580

myString.split("(\\|\\|)|(&&)|(==)|(!=)|(<=)|(>=)|[\\+\\*/%<>]");

I think that should do it - although that will split on all occurrences, not just the first one...

Upvotes: 0

wumpz
wumpz

Reputation: 9131

So this litte program demonstrates how to do this:

public class RegexpSplitter {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(splitString("56&&78&&13")));
        System.out.println(Arrays.toString(splitString("ab==cd")));
    }

    public static String[] splitString(String str) {
        return str.split("\\|\\||&&|==|!=|<|>|<=|>=|\\+|-|\\*|/|%", 2);
    }
}

The output is:

[56, 78&&13]
[ab, cd]

Here is the javadoc of String.split: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29.

There are two implementations. The one I use, allows to specify a limit on how large the result array may be. So on the first occurance of one of your "control" characters the String is split and given back.

Upvotes: 1

Related Questions