Johsh Hanks
Johsh Hanks

Reputation: 147

Using String.split to split with multiple conditions

So I have the following string:

deptid = 33 AND location = 'NewYork'

basically I am trying to parse it into tokens. I have been just using Split.string and separating by space and that would work for everything I need however there are cases where the string might be:

deptid = 33 AND location = 'New York'

I need to keep everything between the quotes the way it is. Is there a way I can use String.split to split it in such a way it will split everything by space except when it encounters quote it will give me the token of everything between the quotes?

EDIT: Sorry for not clarifying earlier! But I want every single thing in that sentence. I want deptid, =, 33, AND, location,=,New York. The AND statement will not always be there. It could just be

location = 'New York'

Upvotes: 2

Views: 2238

Answers (2)

Braj
Braj

Reputation: 46861

Your comment:

I am trying to store it into String[] tokens. So I would expect tokens[0] to be 33 and tokens[1] to be "New York".

Try this one

    String s = "deptid = 33 AND location = 'New York'";

    int index = 0;

    String[] arr = s.split("AND");
    String[] tokens = new String[arr.length];

    for (String str : arr) {
        tokens[index++] = str.split("=")[1].trim();
    }

    for (String token : tokens) {
        System.out.println(token);
    }

Output:

33
'New York'

Upvotes: 3

morgano
morgano

Reputation: 17422

You need something more powerful than just String.split, use Patterns:

String myString = "deptid = 33 AND location = 'New York'";
List<String> tokens = new LinkedList<>();

Pattern tokenPattern = Pattern.compile("'[^']*'|[^ ]+");
Matcher matcher = tokenPattern.matcher(myString);
while(matcher.find()) {
    tokens.add(matcher.group());
}

System.out.println(tokens);

Upvotes: 2

Related Questions