Rasoul Miri
Rasoul Miri

Reputation: 12222

Use regex for split in Java

I have String IR800610000000700805312546 in Java, I need convert to

IR80-0610-0000-0070-0805-3125-46.

I use split for the string, but not work

String[] arrayList = number.split("(\\w{4})");
StringBuilder result = new StringBuilder();
for (int i = 0; i < arrayList.length; i++) {
        result.append(arrayList[i]);
        if (i != arrayList.length - 1) {
            result.append(separator);
        }
}

Can I use String formatter?

Upvotes: 0

Views: 59

Answers (2)

Andy Turner
Andy Turner

Reputation: 140299

It would be easiest just to use a StringBuilder directly, without explicit splitting:

StringBuilder result = new StringBuilder();
String delim = "";
for (int i = 0; i < number.length(); i += 4) {
  result.append(delim);
  delim = "-";

  result.append(number, i, min(i + 4, number.length()));
}

This approach will likely be at least an order of magnitude faster than using regular expressions, because it does far less work.

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163207

You could use replaceall instead of split and use your capturing group followed by a negative lookahead to assert not the end of the string (\w{4})(?!\$).

In the replacement use the capturing group followed by a hyphen $1-

String number = "IR800610000000700805312546";
number = number.replaceAll("(\w{4})(?!$)", "$1-");
System.out.println(number); // IR80-0610-0000-0070-0805-3125-46

Java demo | regex demo

Upvotes: 2

Related Questions