我可以这样做 - token = str.split(“”||“,”);

时间:2013-03-28 19:26:37

标签: java regex split

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 按空格或逗号分割并将其保存到数组令牌[] 我希望输出为: 移动 R1 R2 R3

先谢谢。

3 个答案:

答案 0 :(得分:1)

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

split使用正则表达式作为参数,而正则表达式中的or|。您也可以使用[\\s,] \\s|,,其等于\\s,意味着{{1}} =任意空格(如普通空格,制表符,换行符号)或逗号“。

答案 1 :(得分:0)

你想要

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

方括号表示字符类。此类包含空格和逗号,正则表达式将匹配字符类的任何字符。

答案 2 :(得分:0)

将其更改为strLine.split(" |,"),甚至可能strLine.split("\\s+|,")