将java中的字符串拆分为多个符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18061100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:08:01  来源:igfitidea点击:

Splitting a string in java on more than one symbol

javastringsymbolssplit

提问by Saumyaraj

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.

谢谢。

采纳答案by Mena

String.splittakes 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:

笔记:

  • Reserved characters for Patterns must be double-escaped with \\. Edit: Not needed here.
  • The []brackets in the pattern indicate a character class.
  • More on Patterns here.
  • Patterns 的保留字符必须用\\. 编辑:这里不需要。
  • []模式中的括号表示字符类。
  • 更多关于Patterns在这里

回答by Dennis Kriechel

You need Regular Expression. Addionaly you need the regex ORoperator:

你需要正则表达式。此外,您需要正则表达式OR运算符:

String[]tokens = Stringname.split("\+|\-|\*|\/|\=");

回答by assylias

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.

注意:-应该放在第一个或最后一个位置,以确保它不被视为范围分隔符。

回答by Deactivator2

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