1

Here is a String, I want to split the string such that the symbols and "words" are separate. For example:

String s = "/xyz/abc[bcd(text(),\"string\")]";

I want to have a String array like

String[] result = {"/","xyz","/","abc","[","bcd","(","text","(",")",",","\"","string","\"",")","]"}

How can I do this by using regular expression?

2 Answers 2

3

This should work:

String str = "/xyz/abc[bcd(text(),\"string\")]";

String[] arr = str.split("(?<=\\G(?>\\w+|\\W))\\s*");

This gives:

["/", "xyz", "/", "abc", "[", "bcd", "(", "text", "(", ")", ",", """, "string", """, ")", "]"]

Explanation:

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! What if string has whitespace, I wanna omit this white space while splitting this string? for example String s = "/xyz/abc[ bcd(text(),\"string\")]";
@anubhava nice answer could you explain a bit about what you're trying to do here?
@CSnerd: Hmm so you're chancing the nature of the problem. I am adding my explanation first then I will check whether modified question can be solved this way.
@anubhava I find a way I can use s = s.replaceAll(" ", ""); If modification of answer needs so much work. it is fine.
Glad to know. Also see updated code to discard spaced.
0

User anubhava has answered your question, but in the future http://regexpal.com/ is very helpful when regexing. I use it all the time as a tool, though there are many options.

Helps with trial and error :)

Good luck, happy coding

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.