Want to string split specifically in Java

Arthur :

I want to string split the following String

String ToSplit = "(2*(sqrt 9))/5";

into the following array of String:

String[] Splitted = {"(", "2", "*", "(", "sqrt", "9", ")", ")", "/", "5"};

As you can see the string ToSplit doesn't have spaces and I am having a hard time splitting the word " sqrt " from the rest of the elements because it is a full word. I am doing:

String[] Splitted = ToSplit.split("");

and the word " sqrt " is splitted into {"s", "q", "r", "t"} (obviously) and I want it splitted as the whole word to get the String splitted as shown above

How can I separate the word " sqrt " (as 1 element) from the others ?

Thanks in advance.

Tim Biegeleisen :

Here is a working solution which splits on lookarounds. See below the code for an explanation.

String input = "(2*(sqrt 9))/5";
String[] parts = input.split("(?<=[^\\w\\s])(?=\\w)|(?<=\\w)(?=[^\\w\\s])|(?<=[^\\w\\s])(?=[^\\w\\s])|\\s+");
for (String part : parts) {
    System.out.println(part);
}

(
2
*
(
sqrt
9
)
)
/
5

There are four terms in the regex alternation, and here is what each one does:

(?<=[^\\w\\s])(?=\\w)
split if what precedes is neither a word character nor whitespace, AND
what follows is a word character
e.g. split (2 into ( and 2

(?<=\\w)(?=[^\\w\\s])
 split if what precedes is a word character AND
 what follows is neither a word character nor whitespace
e.g. split 9) into 9 and )

(?<=[^\\w\\s])(?=[^\\w\\s])
split between two non word/whitespace characters
e.g. split )/ into ) and /

\\s+
finally, also split and consume any amount of whitespace
as a separator between terms
e.g. sqrt 9 becomes sqrt and 9

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158897&siteId=1