我想在Java上使用正则表达式来分割数字字符串。 我使用在线正则表达式测试正则表达式是正确的。 但在Java中是错误的。使用正则表达式在java上分割数字字符串
Pattern pattern = Pattern.compile("[\\\\d]{1,4}");
String[] results = pattern.split("123456");
// I expect 2 results ["1234","56"]
// Actual results is ["123456"]
任何遗漏?
我知道这个问题很无聊。但我想解决这个问题。 回答
Pattern pattern = Pattern.compile("[\\d]{1,4}");
String[] results = pattern.split("123456");
// Results length is 0
System.out.println(results.length);
不工作。我已经尝试过了。结果将不会返回任何结果。 请在回答之前尝试。
真诚感谢帮助过我的人。
解决方案:
Pattern pattern = Pattern.compile("([\\d]{1,4})");
Matcher matcher = pattern.matcher("123456");
List<String> results = new ArrayList<String>();
while (matcher.find()) {
results.add(matcher.group(1));
}
输出2次的结果[ “1234”, “56”]
您正在获取一个空数组,因为split会返回分隔符之间的部分*以便分割,并自行丢弃分隔符。也许这有助于:http://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters http://stackoverflow.com/questions/275768/is-there -a-way-split-strings-with-string-split-and-include-the-delimiters – Thilo 2012-03-16 08:12:43
好吧,我现在明白了,谢谢你的帮助。 – 2012-03-16 09:03:15