gpt4 book ai didi

Java 用空白分隔符分割字符串

转载 作者:行者123 更新时间:2023-11-29 03:00:17 25 4
gpt4 key购买 nike

我有一个字符串女巫,我想拆分。我唯一的分隔符是空格。看起来像这样:12 鲍勃马利 22/01/15 0 0 1 1 0

我用这个:

line = br1.readLine();
String[] parts = line.split(" ");
String number = parts[0];
String reference = parts[1];
String date = parts[2];
String one = parts[3];
String sd = parts[4];
String dd = parts[5];
String tt = parts[6];
String vs = parts[7];
System.out.println(
"No:"+number+"Ref:"+reference+"Date:"+date+"One:"+one+"Sd:"+sd+"Dd:"+dd+"Tt:"+tt+"Vs:"+vs);

结果是:

No:12 Ref:BobMarley Date:22/01/15 One:0 Sd:0 Dd:1 Tt:1 Vs:0

如预期。一切都好。

现在,我的问题是字符串是:12 Bob Marley 22/01/15 0 0 1 1 0

或:12 哈利波特与乐队 22/01/15 0 0 1 1 0

输出将是:

No:12 Ref:Bob Date:Marley One:22/01/15 Sd0 Dd:0 Tt:1 Vs:1

预期:12 引用:Bob Marley 日期:22/01/15 ......

知道如何只修剪“否”之间的空白。和“日期”?或者任何其他想法如何获得干净的“Ref”,无论里面有多少个单词。谢谢你!

最佳答案

我建议首先使用正则表达式拆分行以捕获引用部分,然后使用空格拆分以获得结果:

String line = "12 Bob Marley 22/01/15 0 0 1 1 0";

String pattern = "([0-9]+)([a-zA-z|' ']+)(.*)";

Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

if(m.find()) {
System.out.println("No:" + m.group(1));//this will get 12
System.out.println("ref:" + m.group(2));//this will get the name
String[] parts = m.group(3).split(" ");//this is the rest
String date = parts[0];
String one = parts[1];
String sd = parts[2];
String dd = parts[3];
String tt = parts[4];
String vs = parts[5];
System.out.println("Date:"+date+"One:"+one+"Sd:"+sd+"Dd:"+dd+"Tt:"+tt+"Vs:"+vs);
}

关于Java 用空白分隔符分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35468769/

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