2016-11-11 7 views
0

複数の区切り文字で1行ずつファイルを読み込もうとしています。私は分割のために正規表現を使用していますが、区切り文字としてスペース( "")を考慮していません。ファイルには区切り文字として;、#、およびスペースが含まれています。私は間違って何をしていますか? ファイルの行は次のようになります - "R1を追加し、R1、R2、R3Javaで複数の区切り文字を含むファイル行を読み取る

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値)を追加" とR2。スペースを避けるには?正規表現str.split( "[、:;#]")に何か問題はありますか? ?

+2

実際の「」文字の代わりに「\ s」を使用してみてください。 – pathfinderelite

+0

文字セットブラケットの後に 'str.split(" [、:;#] + ");をプラス記号で試してみてください。 – mgaert

+0

http://stackoverflow.com/questions/5200756/which-is-the-best-way-to-parse-a-file-containing-assembly-language-using-java – IceGlow

答えて

0

実際にはスペースですか?

これは、任意のホワイトスペースのために働く必要があります。

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