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

标签 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 根据空格或逗号分割并将其保存到数组 token[] 中 我想要输出为: 移动 R1 R2 R3

提前致谢。

最佳答案

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

split 使用正则表达式作为参数,正则表达式中的 or|。您还可以使用character class就像 [\\s,] 等于 \\s|, 并且意味着 \\s = 任何空格(如普通空格、制表符、换行符)或逗号”。

关于java - 我可以这样做 - token=str.split (""| |",");,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690456/

相关文章:

python - 如何在 Python 中使用空分隔符拆分字符串

Java,为什么要用同步?而不是使用单线程?

python - 使用正则表达式省略数字

python - 在 Python 中分割除特定情况之外的所有内容

.net - 在 Python 中使用 .net 正则表达式

java正则表达式解析部分标题标签

linux - 如何在 %% 或 $$ 中间 grep/split 一个词

java - 如何让 Azure App Service Tomcat 将所有 80/443 流量转发到在同一 App Service 上运行的 JBoss

java - 将 Spring Boot JMS 应用程序配置为默认使用 JAXB 编码的最简单方法是什么?

java - 二叉搜索树递归添加