6

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+)"); 
0

3 Answers 3

9

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 
Sign up to request clarification or add additional context in comments.

Comments

3

You can use this regex fpr splitting:

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

Working Demo

Comments

2

replace the number with the number + a space, then split on space.

a = a.replaceAll("[0-9]+","$1 "); String[] b = a.split(" "); 

It can also be customized in case your string contains other spaces, by substituting a character guaranteed not to appear in your string instead of the space. my favorite is (§).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.