简体   繁体   English

我的split()及其正则表达式出了什么问题?

[英]What's wrong with my split() and its regex?

Part of my application I encountered this problem. 我的部分应用程序遇到了这个问题。 The String line variable contains 12.2 Andrew and I'm trying to split them separately but it doesn't work and comes with a NumberFormatException error. String行变量包含12.2安德鲁 ,我试图分开它们但它不起作用,并带有NumberFormatException错误。 Could you guys help me on that please? 你能帮帮我吗?

String line = "12.2 Andrew";
String[] data = line.split("(?<=\\d)(?=[a-zA-Z])");

System.out.println(Double.valueOf.(data[0]));

Did you look at your data variable? 你看过你的data变量了吗? It didn't split anything at all, since the condition never matches. 它没有任何分裂,因为条件永远不会匹配。 You are looking for a place in the input immediately after a number and before a letter, and since there is a space in between this doesn't exist. 您正在输入一个数字之后和一个字母前面的输入中的位置,并且由于它之间存在空格,因此不存在。

Try adding a space in the middle, that should fix it: 尝试在中间添加一个空间,应该修复它:

String[] data = line.split("(?<=\\d) (?=[a-zA-Z])");

If you print content of data[0] you will notice that it still contains 12.2 Andrew so you actually didn't split anything. 如果你打印data[0]内容,你会发现它仍然包含12.2 Andrew所以你实际上没有拆分任何东西。 That is because your regex says: 那是因为你的正则表达式说:
split on place which has digit before and letter after it 拆分前面有数字的地方和后面的字母

which for data like 对于数据而言

123foo345bar 123 baz

effectively can only split in places marked with | 实际上只能在标有|地方拆分

123|foo345|bar 123 baz
                  ^it will not split `123 baz` like
                   `123| baz` because after digit is space (not letter)
                   `123 |baz` before letter is space (not digit)
                   so regex can't match it

What you need is to " split on space which has digit before and letter after it " so use 你需要的是“ 拆分前面有数字的空格和后面的字母 ”这样使用

String[] data = line.split("(?<=\\d)\\s+(?=[a-zA-Z])");
//                                  ^^^^ - this represent one ore more whitespaces

Your split is not working, and not splitting the String . 您的拆分不起作用,并且不拆分String Therefore Double.parseDouble is parsing the whole input. 因此Double.parseDouble正在解析整个输入。

Try the following: 请尝试以下方法:

String line = "12.2 Andrew";
String[] data = line.split("(?<=\\d)(?=[a-zA-Z])");
System.out.println(Arrays.toString(data));
// System.out.println(Double.valueOf(data[0]));
// fixed
data = line.split("(?<=\\d).(?=[a-zA-Z])");
System.out.println(Arrays.toString(data));
System.out.println(Double.valueOf(data[0]));

Output 产量

[12.2 Andrew]
[12.2, Andrew]
12.2

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

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