基于Java中的多个定界符将字符串拆分为数组 [英] Split String into Array based on multiple delimiters in Java
问题描述
我正在尝试根据多个值将字符串分成两个不同的数组
I am trying to split a string into two different arrays based on multiple values
例如,用户在控制台窗口中输入
For example user inputs in the console window
2+4/8*9
我只希望数字位于数组中
I want only the numbers to be in an array
Arr[0] = 2;
Arr[1] = 4;
Arr[2] = 8;
Arr[3] = 9;
然后
Operator[0] = +;
Operator[1] = /;
Operator[2] = *;
我熟悉只使用一个定界符的split方法,但是如何分割字符串
I am familiar with split method that uses only one delimiter but how will I be able to split the string based on various number of delimiters?
以下是我尝试过的最新代码,通过查看互联网上的各种文章却遇到错误
Following is the latest code I have tried by looking at various articles on the internet but getting error
Scanner in = new Scanner(System.in);
System.out.println("Enter input");
s = in.toString();
String [] operators = s.split("+|-|*|/"); //Also tried s.split("\\+\\-\\*\\/")
for(int i = 0; i<operators.length; i++) {
System.out.println(operators[i]);
}
推荐答案
使用正则表达式,我们可以将表达式并将操作数存储在String []
Using Regex we can split the expression and store the operand in String[]
String [] t = st.split(-| \\#| \ \(| \\)| \\ {| \\} | \\< | \\> | \\s + | \\(\\ \\ | \\;);
正则表达式基于-,#,(,)拆分字符串 ,{,},<,>,空格,;,#
表示(双引号)和(反斜线)之类的字符,然后迭代String的元素并删除字符。
The regex expression split String based on "-, #, (, ), {, }, <, >, space, ;, #" for character like "(double quote) and (backlash) then iterate the elements of String and remove the char.
这篇关于基于Java中的多个定界符将字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!