java - 在java中读取具有多个分隔符的文件行

标签 java regex delimiter readfile

我正在尝试使用多个分隔符逐行读取文件。我使用正则表达式进行分割,但它不考虑空格(“”)作为分隔符。文件包含;、#、、和空格作为分隔符。我究竟做错了什么? 文件行如下所示 - ADD R1, R2, R3

public static void initialize() throws IOException {
    PC = 4000;
    BufferedReader fileReader = new BufferedReader(new FileReader("test/ascii.txt"));
    String str;
    while((str = fileReader.readLine()) != null){
        Instruction instruction = new Instruction();
        String[] parts = str.split("[ ,:;#]");
        instruction.instrAddr = String.valueOf(PC++);
        System.out.println(instruction.instrAddr);
        instruction.opcode = parts[0];
        System.out.println(instruction.opcode);
        instruction.dest = parts[1];
        System.out.println(instruction.dest);
        instruction.source_1 = parts[2];
        System.out.println(instruction.source_1);
        instruction.source_2 = parts[3];
        System.out.println(instruction.source_2);    
    }
    fileReader.close();}

输出打印 4000(PC 值)、ADD、R1、“”和 R2。如何避免空间?正则表达式 str.split("[ ,:;#]"); 有什么问题吗? ?

最佳答案

你确定这些实际上是空格吗?

这应该适用于任何空白:

@Test
public void test() {
    String s = "1 2,3:4;5#6\t7";
    Assert.assertEquals(7, s.split("[\\s,:;#]").length);
}

关于java - 在java中读取具有多个分隔符的文件行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550726/

相关文章:

javascript - 使用正则表达式按 id 获取元素

ssis - 找不到该列的列分隔符

java - 不使用泛型时,确保在关系映射上定义目标实体

java - 将 Access 数据库数据克隆到 H2 之类的内存数据库?

java - 将字符串转换为 byte[] 以使内容保持不变

java - 同步列表如何工作?

regex - 在 linux 中为每个正则表达式匹配添加下划线

regex - 使用正则表达式分割 SparkSQL

c - 使用 strtok() 在 C 中分隔文件路径

java.util.Scanner 的 useDelimiter ("") 或 useDelimiter(Pattern.compile ("\\s")) 与标准行为不同