user1950349
user1950349

Reputation: 5146

Split a string into blocks of three?

I have a String of digits. I need to group those digits in block of length three and separate by single dash. If necessary, the final block or the last two blocks can be of length two.

    String abc = "12-10 23 5555 8361";
    String hello = abc.replaceAll("[^a-zA-Z0-9]", "");

Now, how can I group them in blocks of length three?

Expected result is

121-023-555-583-61

Upvotes: 3

Views: 2177

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

You can use a \G within a lookbehind based regex:

String abc = "12-10 23 5555 8361";
String hello = abc.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(hello.replaceAll("(?<=\\G\\d{3})", "-"));
// => 121-023-555-583-61

See the IDEONE demo

The (?<=\\G\\d{3}) regex contains just a zero-width assertion that matches a position at the start of the string or at the end of the last successful match (\G) that is followed with 3 digits (\d{3}). In Java regex, this pattern works fine in the current scenario (i.e. \G moves the regex index from within lookbehind). This won't work in Android though.

UPDATE:

For the updated requirements, you can use a several step approach like

public static void main (String[] args) throws java.lang.Exception
{
     String s = "0 - 22 1985--324"; // => 022-198-53-24
     run(s);
     s = "555372654";  // => 555-372-654
     run(s);
     s = "12-10 23 5555 8361"; // => 121-023-555-583-61
     run(s);
}
public static void run(String abc) {
    String hello = abc.replaceAll("[^a-zA-Z0-9]", "");
    hello = hello.replaceAll("(?<=\\G\\d{3})(?!$)", "-");
    System.out.println(hello.replaceAll("\\b(\\d{2})(\\d+)-(\\d)$", "$1-$2$3"));
}

See another IDEONE demo

The regex is updated with (?!$) at the end that fails the match at the end of the string.

The .replaceAll("\\b(\\d{2})(\\d+)-(\\d)$", "$1-$2$3") is necessary to re-arrange the 2 last digit groups at the end: if there are 3 or more digits followed with a hyphen and then just 1 digit, we need to move the hyphen after the first 2 digits, and move the other digits right after this hyphen.

Upvotes: 3

user2705585
user2705585

Reputation:

You could also group three digits and replace with captured group and -.

Regex: (\d{3})

Replacement to do: Replace with \1-

Java Code

String abc = "12-10 23 5555 8361";
String hello = abc.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(hello.replaceAll("(\\d{3})", "$1-"));

Regex101 Demo

Ideone Demo

Upvotes: 1

Related Questions