-1

I am trying to convert this string string "4AAC6AA8D5827BA" to into this format "4a:ac:6a:a8:d5:82:7b" using groovy. Could you please asssit

Arulvelu
  • 7
  • 1
  • 7
  • 1
    Please add the code you have tried and how it failed (e.g. errors, stacktraces, logs, ...) so we can improve on it. – cfrick Aug 03 '21 at 15:42
  • Possible duplicate of https://stackoverflow.com/questions/14559878/convert-string-to-macaddress-formate-in-java – cfrick Aug 03 '21 at 15:47

3 Answers3

2

Not sure why you want to ommit the last "A", but the code would do it:

String res = "4AAC6AA8D5827BA".toLowerCase().toList().collate( 2 ).findResults{ 2 == it.size() ? it.join( '' ) : null }.join( ':' )
assert res == '4a:ac:6a:a8:d5:82:7b'
injecteer
  • 20,038
  • 4
  • 45
  • 89
1

This should do the trick:

def addDots(x) { x.toLowerCase().replaceAll(/([0-9a-f]{2})(?!$)/, '$0:') }

This doesn't check that the input is of the correct pattern and will do weird things to anything in a different format.

But addDots("4AAC6AA8D5827BA") will return 4a:ac:6a:a8:d5:82:7b:a

Note that the input you gave has an odd number of characters, which is probably a copy-paste error somewhere.

cfrick
  • 35,203
  • 6
  • 56
  • 68
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • this worked . Yes it is a copy paste error . I am trying to 4AAC6AA8D5827BAD0000000054D021DF which gave me an output as 4a:ac:6a:a8:d5:82:7b:ad:00:00:00:00:54:d0:21:df – Arulvelu Aug 03 '21 at 15:49
1
def addDots(x) { x.toLowerCase().findAll(/..?/).join(':') }
daggett
  • 26,404
  • 3
  • 40
  • 56