Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the way to insert a colon(:) after every two characters in a string?

Tags:

java

string

split

I am trying to figure out that -

INPUT: String data = "506313B5EA3E";

OUTPUT: String data = "50:63:13:B5:EA:3E";

I tried using-

java.util.Arrays.toString(data.split("(?<=\\G..)"))

But the output is: [50, 6313B5EA3E]

like image 704
My God Avatar asked Nov 28 '22 09:11

My God


1 Answers

You can use a RegExp:

String input = "0123456789abcdef";
String output = input.replaceAll("..(?!$)", "$0:")
// output = "01:23:45:67:89:ab:cd:ef"

How does it work?

  • .. matches exactly two characters. (?!$) ensures that these two characters are not at the end of input (?! is a negative lookahead, $ stands for the end).
  • The matching two characters will now be replaced by themselves ($0 means the whole matching string) and the colon we want.
  • Since we are using replaceALL, this operation repeats for every two-character group. Remember: except the last one.
like image 133
theHacker Avatar answered Dec 05 '22 16:12

theHacker