java - How to format string to a particular pattern -
let's have input string , need format this:
### ### ############........etc
so has have first 3 chars, space, 3 chars, space , rest. there third-party library or jdk class able that?
i trying use regular expressions
system.out.println(inputstring.replaceall(".{3}", "$0 "));
but it's not working because result is
### ### ### ### ### etc.
you this:
system.out.println(inputstring.replacefirst("(.{3})(.{0,3})", "$1 $2 "));
explanation:
just $0
entire matched string, $1
, $2
are, respectively, first , second matched things in brackets.
i modified {3}
{0,3}
strings 6 characters or shorter work (it add trailing space when string between 4 , 6 characters, can removed .trim()
(which have unwanted other effects) or more complex).
hopefully no explanation required rest, since it's similar code, feel free ask if you're unsure. java regex reference.
example:
system.out.println("12345678901234567890".replacefirst("(.{3})(.{0,3})", "$1 $2 ")); system.out.println("12".replacefirst("(.{3})(.{0,3})", "$1 $2 ")); system.out.println("12345".replacefirst("(.{3})(.{0,3})", "$1 $2 "));
prints:
123 456 78901234567890 12 123 45
Comments
Post a Comment