简体   繁体   中英

String format into specific pattern

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 3

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM