2

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'

4
  • What would you expect to get when you split that sample? Commented Apr 5, 2014 at 20:11
  • 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". I been separating by space so it would turn out tokens[0] = 33 tokens[1] = New tokens[2] = York and that is not what I want Commented Apr 5, 2014 at 20:14
  • So, are you trying to collect the words after the =, except that if the word is quoted then the quotes need to be removed? Commented Apr 5, 2014 at 20:16
  • I am really sorry I didn't make it clear what I want (tunneled on my problem). I actually want every single word of that sentence but if it has quotes around it I want the entire word. So in the example I want deptid, =, 33, AND, location, =, New York Commented Apr 5, 2014 at 20:20

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

1 Comment

I made a mistake and described what I wanted poorly. Otherwise this would be the correct answer as well
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.