简体   繁体   中英

Java Split String Regex

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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM