Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a String on an Integer followed by a space

I have a rather large String that i need to split so I can put it into an array. As it is, there will be a semicolon followed by an Integer, followed by a space and this is where I need to split it.

Say for instance, I have a String:

 first aaa;0 second bbb;1 third ccc;2

I need to split it so that it becomes:

 first aaa;0 
 second bbb;1
 third ccc;2

I assume I can use something like:

 Pattern pattern = Pattern.compile(^([0-9]*\s");
 myArray = pattern.split(string_to_split);

I just don't understand RegEx that well yet.

Thanks to anyone taking a look

Also, the pattern where it should be split will always be a semicolon, followed by only one digit and then the space.

like image 485
WeVie Avatar asked Sep 19 '14 05:09

WeVie


1 Answers

Just split your input string according to the below regex.

(?<=;\\d)\\s

Code:

String s = "first aaa;0 second bbb;1 third ccc;2";
String[] tok = s.split("(?<=;\\d)\\s");
System.out.println(Arrays.toString(tok));

Output:

[first aaa;0, second bbb;1, third ccc;2]

Explanation:

  • (?<=;\d) Positive lookbehind is used here. It sets the matching marker just after to the ;<number>. That is, it asserts what precedes the space character is must be a semicolon and a number.
  • (?<=;\d)\s Now it matches the following space character.
  • Splitting your input string according to that matched space will give you the desired output.
like image 70
Avinash Raj Avatar answered Oct 26 '22 06:10

Avinash Raj