简体   繁体   English

如何使用正则表达式 Java 拆分此字符串

[英]How to split this String using Regex Java

As the title says I want to split a string specifically but I don´t know what to put inside the String.split("regex")正如标题所说,我想专门拆分一个字符串,但我不知道在 String.split("regex") 中放什么

Say we have:假设我们有:

String s = "sum := A+B*( 99.1 +.44 444 1234+++)-sum/232.123459"

Now I want to split it to put it this way:现在我想把它拆分成这样:

String[] splitted = ["sum"; ":="; "A"; "+"; "B"; "*"; "("; "99.1"; "+"; ".44"; "444"; "1234"; "+"; "+"; "+"; ")"; "-"; "sum"; "/"; "232.123459"]

So, basically I want to split by space, words, the math operators, numbers, the parenthesis, the letters and the number ".44" has to remain this way.所以,基本上我想按空格、单词、数学运算符、数字、括号、字母和数字“.44”分开,必须保持这种方式。

Can you help me?你能帮助我吗? Thanks in advance提前致谢

Don't use split() .不要使用split() Use a find() loop.使用find()循环。

String regex = "[0-9]+\\.?[0-9]*" + // Match number (e.g. 999 or 999.99)
              "|\\.[0-9]+" +        // Match number (e.g. .999)
              "|[a-zA-Z]\\w*" +     // Match identifier
              "|:=" +  // Match complex operator
              "|\\S";  // Match other single non-space, incl. operators: +, -, *, /, (, )

Test测试

String s = "sum := A+B*( 99.1 +.44 444 1234+++)-sum/232.123459";
String[] splitted  = Pattern.compile(regex).matcher(s).results()
        .map(MatchResult::group).toArray(String[]::new);
System.out.println(Arrays.toString(splitted));

Output输出

[sum, :=, A, +, B, *, (, 99.1, +, .44, 444, 1234, +, +, +, ), -, sum, /, 232.123459]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM