gpt4 book ai didi

java - java中如何将字符串拆分为数字和字符

转载 作者:行者123 更新时间:2023-12-02 01:26:28 30 4
gpt4 key购买 nike

我需要分割一个包含一系列数字和字符的字符串。数字可以有小数位。它还必须考虑到字符串可以有或没有空格。我需要弄清楚如何使用正确的正则表达式。

我尝试了不同的 .split() 配置,但它没有按照我希望的方式工作。

static int getBytes (String text) {

//the string is split into two parts the digit and the icon
String[] parts = text.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
double num = Double.parseDouble(parts[0]);
String icon = parts[1];

// checks if the user enters a valid input
if(parts.length > 2 || icon.length() > 3) {
System.err.println("error: enter the correct format");
return -1;
}

return 0;
}
 if i have a string text = "123.45kb"; i expect = "123.45", "kb"
or text = "242.24 mg"; i expect = "242.24", "mg"
or text = "234 b" i expect = "234", "b"

最佳答案

当前查找中的逻辑问题是 \\D 匹配任何非数字字符。这确实包括字母(例如 kb),但也包括 . 以及任何其他非数字字符。尝试仅在数字和字母之间进行拆分:

String text = "123.45 kb";
String[] parts = text.split("(?<=[A-Za-z])\\s*(?=\\d)|(?<=\\d)\\s*(?=[A-Za-z])");
System.out.println(Arrays.toString(parts));

打印:

[123.45, kb]

关于java - java中如何将字符串拆分为数字和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844183/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com