gpt4 book ai didi

java - 匹配 ":"之后包含的字符串的正则表达式

转载 作者:行者123 更新时间:2023-12-01 06:32:48 24 4
gpt4 key购买 nike

我需要使用 scan.useDelimiter() 来识别“:”之后发生的字符串。

我正在制作一个扫描仪,它从类似条目的列表中获取以下行。

c : 20002 : The Dragon :     Dreama : 10000 :   1 :  22 :   9 :  237.20 :   60.47 :  354.56

这是我到目前为止所拥有的:

    public Boolean readFile (){ //Fix tomorrow
while ( input.hasNext () ) {
char x = stat.next().charAt(0);
String line = input.nextLine().trim();
Scanner stat = new Scanner(line).useDelimiter("\\s*:\\s*")

if( line.length()== 0 || input.next().charAt(0) == '/' ) continue;
switch ( x ) {
case 'c' :
int a = stat.nextInt();
String b = stat.next();
break;
case 't' :
//...

由于某种原因,我无法正确扫描。对于上面的条目,我需要以下字符串。

20002, The Dragon, Dreama, 10000, etc.

如您所见,我需要忽略短语边缘的空格,但如果短语之间有空格(例如“The Dragon”),则需要保留该空格。

以下问题对我没有帮助: Question 1/ Question 2

最佳答案

只需使用 String.split() :

String line = input.nextLine().trim();
String[] tokens = line.split("\\s*:\\s*");

请注意,我只是在您的问题中重复使用正则表达式。您的正则表达式将删除每个标记中所有多余的前导和尾随空格。仍然需要对整个输入进行 trim() 来删除前导空格和尾随空格,而 split() 方法中的正则表达式不匹配并且不会触及这些空格。

关于java - 匹配 ":"之后包含的字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17070085/

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