gpt4 book ai didi

java - 基于整数定界符在java中拆分字符串

转载 作者:行者123 更新时间:2023-11-29 05:32:39 25 4
gpt4 key购买 nike

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

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.

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

最佳答案

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

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.]

关于java - 基于整数定界符在java中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20596272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com