Java 如何使用正则表达式仅使用行的一部分?(爪哇)

Java 如何使用正则表达式仅使用行的一部分?(爪哇),java,regex,Java,Regex,在提供的文件的每一行中,每一行都遵循以下结构: 8个数字,然后是1个逗号,然后是2个数字。 例如: 98468631,51 我只想使用逗号后的两位数字 节目如下: import java.io.*; import java.util.regex.*; public class Read { public static void main(String[] args) { String[] marks = new String[100]; File file = new Fi

在提供的文件的每一行中,每一行都遵循以下结构:

8个数字,然后是1个逗号,然后是2个数字。

例如: 98468631,51

我只想使用逗号后的两位数字

节目如下:

import java.io.*;
import java.util.regex.*;

public class Read {

public static void main(String[] args) {
    String[] marks = new String[100];

    File file = new File("sd100-marks.csv");

    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));

        for(int i = 0; i < 100; i++) {
            try {
                String line = reader.readLine();
                String[] sp = line.split(",");
                line = sp[0];
                marks[i] = line;
            } catch (IOException e) {
                System.out.println("Could not read!");
            }
        }


    } catch (FileNotFoundException e) {
        System.out.println(e);
    }
    for(int i = 0; i < 100; i++) {
        System.out.println(marks[i]);
    }

  }

}
import java.io.*;
导入java.util.regex.*;
公开课阅读{
公共静态void main(字符串[]args){
字符串[]标记=新字符串[100];
文件文件=新文件(“sd100 marks.csv”);
试一试{
BufferedReader reader=新的BufferedReader(新文件读取器(文件));
对于(int i=0;i<100;i++){
试一试{
字符串行=reader.readLine();
字符串[]sp=line.split(“,”);
line=sp[0];
标记[i]=直线;
}捕获(IOE异常){
System.out.println(“无法读取!”);
}
}
}catch(filenotfounde异常){
系统输出打印ln(e);
}
对于(int i=0;i<100;i++){
系统输出打印LN(标记[i]);
}
}
}

基本上,我不确定在
split()
方法中使用什么正则表达式。目前,我已将“”传递给该方法,但这对我尝试执行的操作没有用处,只显示逗号前的所有数字。

Sring.split
确实是要使用的方法

String[] sp = line.split(",");
//sp[0] contains the first 8 digits
//sp[1] contains the part after the ",".
因此,请使用:

line = sp[1];//instead of sp[0]

这似乎是错误的,因为你正在尝试做你得到的第一部分:

line = sp[0];
尝试获取第二部分,您还应该检查
sp
中是否有两个部分:

if (sp.length > 1) {
    line = sp[1];
}

split方法的工作原理类似于使用给定表达式和零限制参数调用双参数split方法。因此,结果数组中不包括尾随的空字符串

例如,字符串“boo:and:foo”使用以下表达式生成以下结果:

Regex   Result
:   { "boo", "and", "foo" }
o   { "b", "", ":and:f" }
试试看

String line = "98468631,51";
String[] sp = line.split(",");
System.out.println(sp[0]);//98468631
System.out.println(sp[1]);//51


如果您确实想使用正则表达式,可以使用以下正则表达式,并且可以提取组:([0-9]),([0-9])
然后第(2)组会在逗号后给出数字。有关详细信息,请参阅文档。

重要说明:不要在
for
循环中使用
String.split()

在这种情况下使用
模式/匹配器
更有效

String[] marks = new String[100];
Pattern pattern = Pattern.compile(","); // <== this
File file = new File("sd100-marks.csv");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
    for (int i = 0; i < 100; i++) {
        marks[i] = pattern.split(reader.readLine())[1]; // we need the part after the comma i.e. index = 1
    }
} catch (IOException e) {
    e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
    System.out.println(marks[i]);
}
String[]标记=新字符串[100];
Pattern=Pattern.compile(“,”)//