Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex split string after number [duplicate]

Tags:

java

regex

Sorry, yet another regex question! I have a string of unknown length that contains the following pattern:

"abc1defg2hijk23lmn19"

I need to split the string to get the following:

["abc1", "DefG2", "hiJk23", "lmn19"]

Its pretty simple I just need to split after the number each time. The number can be any non zero number.

I can do a positive lookup like this:

a.split("(?=\\d+)");

However, that actually splits out the number rather than the group of letter in front and the number.

My current attempt looks like this but doesn't work:

a.split("(?=[A-Za-z]+\\d+)");
like image 732
tarka Avatar asked Jun 26 '14 13:06

tarka


2 Answers

So for input

abc1defg2hijk23lmn19

you want to find places marked with |

abc1|defg2|hijk23|lmn19

In other words you want to find place which

  • has digit before (?<=[0-9])
  • and alphabetic after (?=[a-zA-Z]) it

(I assume you are familiar with look-around mechanisms).

In that case use

split("(?<=[0-9])(?=[a-zA-Z])")

which means place between digit and alphabetic character like 1|a where | represents such place.


Example:

String data ="abc1defg2hijk23lmn19";
for (String s: data.split("(?<=[0-9])(?=[a-zA-Z])"))
    System.out.println(s);

Output:

abc1
defg2
hijk23
lmn19
like image 128
Pshemo Avatar answered Sep 28 '22 01:09

Pshemo


You can use this regex fpr splitting:

(?<=\\d)(?=\\D)

Working Demo

like image 38
anubhava Avatar answered Sep 28 '22 03:09

anubhava