0

Is there a way using Java String.split(regexp) to split on strings inside of quotes, and not get the quotes? The strings I have to deal with are like the following. I don't have control of the format and the number of strings are variable:

"strA" : "strB" : "strC" : "strD",
"strE" : "strF" : "strG",

Note: The spaces are included, and each line is handled separately. So what I would like to get is an array with all strings.

I could use replaceAll to strip the quotes, spaces and commas, then split on the colon:

line = line.replaceAll(/(\"|,\\s+)/,"");
usrArray = line.split(":");

But I'd like to do this with one regexp.

7
  • 1
    Looks like a JSON. You might consider just parsing the JSON string. Commented Mar 30, 2018 at 21:03
  • show us more of what you are parsing. it seems like the data you are trying to parse is JSON and there exist parsers for that type of format already Commented Mar 30, 2018 at 21:17
  • This is not a JSON, it's actually a series of strings in quotes separated by colons, I just included two with user/role names for simplicity. I've updated the post to be more specific. Commented Mar 30, 2018 at 21:17
  • so whats wrong with line.split(":") and then for each piece in the array you trim().replaceAll(""", ""); ?? you could line.split(""\\s+:\\s+"") but it wouldn't fully clean up the pieces for the first and last item in the array returned Commented Mar 30, 2018 at 21:20
  • Nothing wrong with that or the way I did it with replace, and split on the colon. I wanted to do it one regular expression so that it is one operation as opposed to two if possible. Commented Mar 30, 2018 at 21:22

1 Answer 1

1

This should do the trick.

usrArray = line.split("(\" : \")|(\",?)");

This looks first for " : ". If it doesnt find that it will look for the edge cases, " and ",. If you need it to also search for newlines, use this regex.

usrArray = line.split("(\" : \")|(\",?\n?)");
Sign up to request clarification or add additional context in comments.

1 Comment

That's really close! I'm still getting an empty string as the first element in the returned array, but I can work around that.

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.