在整数上拆分字符串,后跟空格

时间:2022-08-22 12:54:55

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.

我还不太了解RegEx。

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.

此外,它应该被分割的模式将始终是分号,后面只有一个数字,然后是空格。

1 个解决方案

#1


19  

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)这里使用正面观察。它将匹配标记设置在; 之后。也就是说,它声明空格字符必须是分号和数字之前的内容。
  • (?<=;\d)\s Now it matches the following space character.
  • (?<=; \ d)\ s现在它匹配以下空格字符。
  • Splitting your input string according to that matched space will give you the desired output.
  • 根据匹配的空间拆分输入字符串将为您提供所需的输出。

#1


19  

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)这里使用正面观察。它将匹配标记设置在; 之后。也就是说,它声明空格字符必须是分号和数字之前的内容。
  • (?<=;\d)\s Now it matches the following space character.
  • (?<=; \ d)\ s现在它匹配以下空格字符。
  • Splitting your input string according to that matched space will give you the desired output.
  • 根据匹配的空间拆分输入字符串将为您提供所需的输出。