Reputation: 203
my string contains
{my office opens 24/7, if you have any question (query) contact with us.}
and i want to break it into
{my}, {office}, {opens}, {24},{/}, {7}, {,}, {if}, {you}, {have}, {any}, {question}, {(}, {query}, {)}, {contact}, {with}, {us}, {.}
means, if single literal of string is only contains characters or numbers separate it. if literal contain special character with characters or numbers, separate the characters before the special character, separate special character and separate characters after the special characters
I am looking for any solution, by using string.split(), or by using any other alternative logic. thanks in Advance.
Upvotes: 0
Views: 51
Reputation: 552
I will add up to your answer, as you had a very good regex! As i figured out this answer still leaves some whitespaces. I added some lines to generate the exact output that was asked. :-)
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
String str = "my office opens 24$7, if you have any question (query) contact with us.";
String[] split = str.split("(?=[\\W])|(?<=[\\W])|\\s");
ArrayList<String> finalList = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
if (!split[i].equals(" ")) {
finalList.add(split[i]);
}
}
//Test
for (String i : finalList) {
System.out.println(i);
}
}
}
Upvotes: 1
Reputation: 3917
You can try this:
String str = "my office opens 24/7, if you have any question (query) contact with us.";
String[] splited = str.split("(?=[()./,])|(?<=[()./,])|\\s");
UPDATE
As pointed by Rafael Battesti, this solution does not work with other specials characters like '@' or '%' for instance.
So, I think you could change the regex to
String[] splited = str.split("(?=[\\W])|(?<=[\\W])");
Upvotes: 2