Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java (Regex?) split string between number/letter combination

I've been looking through pages and pages of Google results but haven't come across anything that could help me.

What I'm trying to do is split a string like Bananas22Apples496Pears3, and break it down into some kind of readable format. Since String.split() cannot do this, I was wondering if anyone could point me to a regex snippet that could accomplish this.

Expanding a bit: the above string would be split into (String[] for simplicity's sake):

{"Bananas:22", "Apples:496", "Pears:3"}
like image 925
Timr Avatar asked Nov 14 '12 06:11

Timr


2 Answers

Try this

String s = "Bananas22Apples496Pears3";

String[] res = s.replaceAll("(?<=\\p{L})(?=\\d)", ":").split("(?<=\\d)(?=\\p{L})");
    for (String t : res) {
        System.out.println(t);
    }

The first step would be to replace the empty string with a ":", when on the left is a letter with the lookbehind assertion (?<=\\p{L}) and on the right is a digit, with the lookahead assertion (?=\\d).

Then split the result, when on the left is a digit and on the right is a letter.

\\p{L} is a Unicode property that matches every letter in every language.

like image 142
stema Avatar answered Sep 29 '22 00:09

stema


You need to Replace and then split the string.You can't do it with the split alone

1> Replace All the string with the following regex

(\\w+?)(\\d+)

and replace it with

$1:$2

2> Now Split it with this regex

(?<=\\d)(?=[a-zA-Z])
like image 45
Anirudha Avatar answered Sep 28 '22 22:09

Anirudha