1
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class TrimTest{
public static void main(String args[]) throws IOException{
String[] token = new String[0];
String opcode;
String strLine="";
String str="";
    try{
        // Open and read the file
        FileInputStream fstream = new FileInputStream("a.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        //Read file line by line and storing data in the form of tokens
        if((strLine = br.readLine()) != null){
            token = strLine.split(" ");// split w.r.t spaces 
                            token = strLine.split(" "||",")   // split if there is a space or comma encountered
            }
        in.close();//Close the input stream
    }
    catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
    int i;
    int n = token.length;
    for(i=0;i<n;i++){
        System.out.println(token[i]);
        }
}
}

如果输入 MOVE R1,R2,R3 相对于空格或逗号拆分并将其保存到数组 token[] 我希望输出为: MOVE R1 R2 R3

提前致谢。

4

3 回答 3

1

Try token = strLine.split(" |,").

split uses regex as argument and or in regex is |. You can also use character class like [\\s,] which is equal to \\s|, and means \\s = any white space (like normal space, tab, new line mark) OR comma".

于 2013-03-28T19:27:50.510 回答
0

You want

token = strLine.split("[ ,]"); // split if there is a space or comma encountered

Square brackets denote a character class. This class contains a space and a comma and the regex will match on any character of the character class.

于 2013-03-28T19:27:40.977 回答
0

Change it to strLine.split(" |,"), or maybe even strLine.split("\\s+|,").

于 2013-03-28T19:28:34.477 回答