0

Is there any pretty and flexible way to format String data into specific pattern, for example:

data input -> 0123456789
data output <- 012345/678/9

I did it by cutting String into multiple parts, but I'm searching for any more suitable way.

1
  • 3
    Post your attempt Commented Apr 23, 2018 at 17:53

3 Answers 3

1

Assuming you want the last and 4th-2nd last in groups:

String formatted = str.replaceAll("(...)(.)$", "/$1/$2");

This captures the parts you want in groups and replaces them with intervening slashes.

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

Comments

1

You can use replaceAll with regex to match multiple groups like so :

String text = "0123456789";
text = text.replaceAll("(\\d{6})(\\d{3})(.*)", "$1/$2/$3");
System.out.println(text);

Output

012345/678/9

details

  • (\d{6}) group one match 6 digits
  • (\d{3}) group two match 3 digits
  • (.*) group three rest of your string
  • $1/$2/$3 replace with the group 1 followed by / followed by group 2 followed by / followed by group 3

Comments

0

You can use StringBuilder's insert to insert characters at a certain index:

String input = "0123456789";
String output = new StringBuilder(input)
    .insert(6, "/")
    .insert(10, "/")
    .toString();
System.out.println(output); // 012345/678/9

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.