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"};
To do this I use:
String[] Splitted = ToSplit.split("(?<=[^\\w\\s])(?=\\w)|(?<=\\w)(?=[^\\w\\s])|(?<=[^\\w\\s])(?=[^\\w\\s])|\\s+");
and it works perfectly, BUT, in other tests it envolves doubles, for example
String toSplit = " 2*sqrt(3.0) ";
and I want to split it this way:
String[] Splitted = {"2", "*", "sqrt", "(", "3.0", ")"};
But it is coming out
String[] Splitted = {"2", "*", "sqrt", "(", "3", ".", "0", ")"};
So, as you can see, in spite of having just the element "3.0" I get three elements {"3", ".", "0"}
How can I solve this issue?
Thanks in advance.
As an option, you can just concatenate the elements you need (this is just a sample code, I did not test it):
String[] splitted = {"2", "*", "sqrt", "(", "3", ".", "0", ")"};
List<String> a = new ArrayList<>();
for (int i = 0; i < splitted.length(); i++) {
if (splitted[i].equals(".") && i > 0 && i < splitted.length() - 1) {
a.set(a.size() - 1, a.get(i - 1) + "." + splitted[i + 1]);
i+=2;
} else {
a.add(splitted[i]);
}
}
//The elements you need are on the 'a' list.
But I suggest you following John Bollinger's advice. Write your own simple parser to split the input String. That is not that hard.
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.