简体   繁体   中英

Reading file line with multiple delimiters in java

I am trying to read a file line by line with multiple delimiters. I am using a regex for splitting but its not considering space (" ") as a delimiters. File contains ;, #, ,, and space as delimiters. What am I doing wrong? File line looks like this - 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();}

The output prints 4000 (PC value), ADD, R1, " " and R2. How to avoid space? Is there anything wrong with the regex str.split("[ ,:;#]"); ?

Are you sure those are actually spaces?

This should work for any white-space:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM