0

I want to using regex on Java to split a number string. I using a online regex tester test the regex is right. But in Java is wrong.

Pattern pattern = Pattern.compile("[\\\\d]{1,4}");
String[] results = pattern.split("123456");
// I expect 2 results ["1234","56"]
// Actual results is ["123456"]

Anything do I missing?


I knows this question is boring. But I wanna to solve this problem. Answer

Pattern pattern = Pattern.compile("[\\d]{1,4}");
String[] results = pattern.split("123456");
// Results length is 0
System.out.println(results.length);

is not working. I have try it. It's will return nothing on the results. Please try before answer it.

Sincerely thank the people who helped me.


Solution:

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));
}

Output 2 results ["1234","56"]

1

3 Answers 3

5
Pattern pattern = Pattern.compile("[\\\\d]{1,4}")

Too many backslashes, try [\\d]{1,4} (you only have to escape them once, so the backslash in front of the d becomes \\. The pattern you wrote is actually [\\d]{1,4} (a literal backslash or a literal d, one to four times).

When Java decided to add regular expressions to the standard library, they should have also added a regular expression literal syntax instead of shoe-horning it over Strings (with the unreadable extra escaping and no compile-time syntax checking).

Sign up to request clarification or add additional context in comments.

1 Comment

Pattern pattern = Pattern.compile("\\d{1,4}"); String[] results = pattern.split("123456"); The results length is zero.
1

Solution:

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));
}

Output 2 results ["1234","56"]

Comments

1

You can't do it in one method call, because you can't specify a capturing group for the split, which would be needed to break up into four char chunks.

It's not "elegant", but you must first insert a character to split on, then split:

String[] results = "123456".replaceAll("....", "$0,").split(",");

Here's the output:

System.out.println(Arrays.toString(results)); // prints [1234, 56]

Note that you don't need to use Pattern etc because String has a split-by-regex method, leading to a one-line solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.