Divide the string by an integer followed by a space

I have a fairly large String that I need to split, so I can put it in an array. Be that as it may, there will be a semicolon followed by Integer , followed by a space, and here I need to break it.

Say for example, I have a String :

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

I need to break it down 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 don't understand RegEx yet, but for now.

Thanks, who is watching.

In addition, the pattern in which it should be divided will always be a semicolon, followed by only one digit, and then a space.

+5
source share
1 answer

Just split the input line according to the expression below.

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

the code:

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

Conclusion:

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

Explanation:

  • (?<=;\d) A positive lookbehind is used here. It sets the appropriate marker immediately after ;<number> . That is, he claims that precedes the space character, there must be a semicolon and a number.
  • (?<=;\d)\s Now it matches the next space character.
  • Splitting the input string according to this consistent space will give you the desired result.
+19
source

Source: https://habr.com/ru/post/1202937/


All Articles