[英]Splitting a string in java on more than one symbol
I want to split a string when following of the symbols encounter "+,-,*,/,=" I am using split function but this function can take only one argument.Moreover it is not working on "+". 我希望在符号遇到“+, - ,*,/,=”之后拆分字符串。我使用的是分割函数,但是这个函数只能使用一个参数。而且它不能用于“+”。 I am using following code:- 我使用以下代码: -
Stringname.split("Symbol");
Thanks. 谢谢。
String.split
takes a regular expression as argument. String.split
将正则表达式作为参数。
This means you can alternate whatever symbol or text abstraction in one parameter in order to split your String
. 这意味着您可以在一个参数中交替使用任何符号或文本抽象,以便拆分String
。
See documentation here . 请参阅此处的文档
Here's an example in your case: 以下是您案例中的示例:
String toSplit = "a+b-c*d/e=f";
String[] splitted = toSplit.split("[-+*/=]");
for (String split: splitted) {
System.out.println(split);
}
Output: 输出:
a
b
c
d
e
f
Notes: 笔记:
You can use a regular expression: 您可以使用正则表达式:
String[] tokens = input.split("[+*/=-]");
Note: -
should be placed in first or last position to make sure it is not considered as a range separator. 注意: -
应放在第一个或最后一个位置,以确保它不被视为范围分隔符。
You need Regular Expression. 你需要正则表达式。 Addionaly you need the regex OR
operator: Addionaly你需要正则表达式OR
运算符:
String[]tokens = Stringname.split("\\+|\\-|\\*|\\/|\\=");
For that, you need to use an appropriate regex statement. 为此,您需要使用适当的正则表达式语句。 Most of the symbols you listed are reserved in regex, so you'll have to escape them with \\
. 您列出的大多数符号都保留在正则表达式中,因此您必须使用\\
来转义它们。
A very baseline expression would be \\+|\\-|\\\\|\\*|\\=
. 一个非常基线的表达式是\\+|\\-|\\\\|\\*|\\=
。 Relatively easy to understand, each symbol you want is escaped with \\
, and each symbol is separated by the |
比较容易理解,你想要的每个符号都用\\
来转义,每个符号用|
分隔 (or) symbol. (或)符号。 If, for example, you wanted to add ^
as well, all you would need to do is append |\\^
to that statement. 例如,如果您想要添加^
,那么您需要做的就是将|\\^
附加到该语句。
For testing and quick expressions, I like to use www.regexpal.com 对于测试和快速表达,我喜欢使用www.regexpal.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.