简体   繁体   English

为什么在 Java 中尝试拆分字符串时出现空字符串? 以及如何解决?

[英]Why there are empty string while trying to split a string in Java? And how to fix it?

I am trying to split a string like this:我正在尝试拆分这样的字符串:

stringNumbers = "12.34+345.56+45-87.90*43.00";
String[] Operators = stringNumbers.split("[0-9.]");

in the console when I print operators I am getting this:在控制台中,当我打印运算符时,我得到了这个:

[, , , , , +, , , , , , +, , -, , , , , *]

The null characters are not my desired output. null 字符不是我想要的 output。 Why am I getting null charachters and how to solve the problem?为什么我得到 null 字符以及如何解决问题?

It's because you're splitting by a single character, you would have to do this eagerly:这是因为您要按单个字符进行拆分,因此您必须急切地这样做:

String[] Operators = stringNumbers.split("[0-9.]*");

Or you can filter the results:或者您可以过滤结果:

String[] Operators = Arrays.stream(stringNumbers.split("[0-9.]"))
    .filter(str -> !str.equals(""))
    .toArray(String[]::new);

Another option would be to just collect those numbers, with a simple expression such as:另一种选择是只收集这些数字,使用简单的表达式,例如:

\\d+(?:\\.\\d+)?

Test测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex = "\\d+(?:\\.\\d+)?";
        final String string = "12.34+345.56+45-87.90*43.00\n"
             + "12+345+45.8-87*43";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

Output Output

Full match: 12.34
Full match: 345.56
Full match: 45
Full match: 87.90
Full match: 43.00
Full match: 12
Full match: 345
Full match: 45.8
Full match: 87
Full match: 43

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com .如果您想简化/修改/探索表达式,它已在regex101.com的右上角面板上进行了解释。 If you'd like, you can also watch in this link , how it would match against some sample inputs.如果您愿意,您还可以在此链接中观看它如何与一些示例输入匹配。


RegEx Circuit正则表达式电路

jex.im visualizes regular expressions: jex.im可视化正则表达式:

在此处输入图像描述

String stringNumbers = "12.34+345.56+45-87.90*43.00"; String[] Operators = Arrays.stream(stringNumbers.split("[0-9.]+")) .filter(str -> !str.equals("")) .toArray(String[]::new);

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

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