Reputation: 91
I have a String
String s = "XXXX....XXX.....XX";
I want the following results.
String[] strings = {"XXXX", "XXX", "XX"};
I tried the following.
String[] split = s.split("[\\.*]");
i got the result
How should I do this if possible?
Upvotes: 2
Views: 56
Reputation: 18611
Another way:
String[] results = string.split("(?:\\Q.\\E)+");
See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
(?: group, but do not capture (1 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
\Q start of a literal string pattern
--------------------------------------------------------------------------------
. a literal dot
--------------------------------------------------------------------------------
\E end of a literal string pattern
--------------------------------------------------------------------------------
)+ end of grouping
Upvotes: 1
Reputation: 626893
To split with multiple dots and avoid empty items, you can use
String[] chunks = s.split("\\.+");
String[] chunks = s.replaceFirst("^\\.+", "").split("\\.+");
NOTE: the replaceFirst("^\\.+", "")
is necessary in case there are leading dots. If you are sure there can be no leading dots, you may use s.split("\\.+")
alone.
Details:
^
- start of string\.+
- one or more dot chars (in a Java string literal, the backslash is doubled)See the Java demo online:
String s = "...XXXX....XXX.....XX...";
String[] chunks = s.replaceFirst("^\\.+", "").split("\\.+");
System.out.println(Arrays.toString(chunks));
Upvotes: 3