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.
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.
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 3You 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