Reputation: 1033
I am looking to split a string (keeping all groups) by a number value. For example datasource10
would give ["datasource","10"]
.
I've tried using:
String[] key = "datasource10".split("(?=\\d)");
However thats not returning "10", but rather ["datasource","1","0"]
. How can I change it to return ["datasource","10"]
?
Upvotes: 0
Views: 29
Reputation: 124225
You can add a condition which will also require the left side to be a non-digit (\D
). To do so you can use a look-behind like:
.split("(?<=\\D)(?=\\d)")
But current solution will split in a way foo123bar
->foo
123bar
since you are only splitting between non-digit|digit.
If you would also want to split between 123bar
(digit|non-digit) simply reverse current regex and add it with OR operator like
.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")
Upvotes: 2