基于整数分隔符在java中拆分字符串

时间:2013-12-15 15:38:10

标签: java regex arrays string

我正在尝试根据基于的整数分割几个字符串,同时仍保留整数。

String theMessage = "1. First String. 2. Second String. 10. Tenth String. 20. Twentieth String.";
String delims = "(?<=(0*([0-9]{1,2}|100)))";
String[] questions = theMessage.split(delims);  
System.out.println(Arrays.toString(questions));

但它将它们分开为:

1. First String. 2 
 . Second String. 1 
1 
0 
 . Tenth String. 2 
0 \n
 . Twentieth String 

但我希望他们像这样分开:

1. First String.
2. Second String.
10. Tenth String.
20. Twentieth String.

基本上我希望每个分离的部分都是数组中的不同元素。

1 个答案:

答案 0 :(得分:2)

您可以在整数前面的空格上拆分,从而将每个组作为数组元素。

String s = "1. First String. 2. Second String. 10. Tenth String. 20. Twentieth String.";
String[] parts = s.split("\\s+(?=[0-9])");
System.out.println(Arrays.toString(parts));

请参阅Live demo

输出

[1. First String., 2. Second String., 10. Tenth String., 20. Twentieth String.]