1

I need to format a string that contains a MAC address (for logging). The string is of the format "xxxxxxxxxxxx" and I need to standardize it to "xx-xx-xx-xx-xx-xx". Whats a good regex for this purpose?

I'm compiling C++ code using GCC 4.4.7. Also, I'd prefer to use boost regex. However, if there are any simpler alternatives please let me know. This is what I have so far

std::string s = "e8f5a4b3e8e4";
boost::regex expr("^ *([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2}) *$", boost::regex::extended | boost::regex::icase);
std::string fmt{"\\1-\\2-\\3-\\4-\\5-\\6"};
std::cout << boost::regex_replace(s, expr, fmt) << '\n';

I'd like to know if there's an optimized version of the regex that I'm using. I've tried this regex - ^ *([[:xdigit:]]{2}){6} *$ at https://regex101.com but it doesn't capture all the groups. It captures only the last one.

Muru
  • 93
  • 1
  • 1
  • 7

1 Answers1

0

First of all, this is not the right answer but I'm posting it since it might help you. I'm not sure if this works for C++ as it works for other languages.

You can try a regex like this:

(\w{2})
or
(.{2})
or
([[:xdigit:]]{2})

Example demo

And use a replacement string as \\1-. For instance, in javascript you could have something like this:

var re = /(\w{2})/g; 
var result = 'e8f5a4b3e8e4'.replace(re, '$1-');
// result => e8-f5-a4-b3-e8-e4

The idea of this is to replace each two characters by the same characters plus a hyphen.

Again, I'm not sure if you have a similar feature in c++ but if it does this answer can help you. I can delete if it doesn't.

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123