0

i have an example string like the one below

http://rp-F083B8.local/?mac=00:26:32:F0:83:B8&nav=4702&hw=STEM_125-14_v1.0

from this text i need to extract the mac address from the middle, but without the semicolon in-between.

i have managed to do this in 2 expresion like this: (\w{2})[:](\w{2})[:](\w{2})[:](\w{2})[:](\w{2})[:](\w{2}) ==> 00:26:32:F0:83:B8

and another /\W/ applied to the previous result ==> 002632F083B8

but the requirement is to do this in just one expression. is there another way to do this in just expression? thanks,

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Do it with regex `replace` method. See https://regex101.com/r/w0IamZ/1. Note you can't match disjoint pieces of text within 1 match operation. Thus, you need to replace/match multiple occurrences + join. – Wiktor Stribiżew Mar 11 '20 at 12:03
  • Please let know your programming environment – Wiktor Stribiżew Mar 12 '20 at 11:53
  • my programming language is C# and C++. i will try this way, if just one expression cannot be achieved. thank you – JustSilviu Mar 12 '20 at 13:07
  • No, there should be one per question, else, it is too broad. These two are quite different, please choose one, and update the question with the code that fails. – Wiktor Stribiżew Mar 12 '20 at 13:08

1 Answers1

1

I'm not sure if this satisfies your requirement of single expression

#include<regex>
#include<string>
#include<iostream>

std::string foo(std::string s)
{
    // match the mac address, but don't capture colons
    static const std::regex r {R"~~(^.*mac=(\w{2}):(\w{2}):(\w{2}):(\w{2}):(\w{2}):(\w{2}).*$)~~"};
    // join the 6 bits together
    return std::regex_replace(s, r, "$1$2$3$4$5$6"); 
}

int main()
{
    std::string s = "http://rp-F083B8.local/?mac=00:26:32:F0:83:B8&nav=4702&hw=STEM_125-14_v1.0";
    std::cout << foo(s);
}

This is 2 regexes but easier to understand

std::string foo(std::string s)
{
    static const std::regex mac_address {R"~~(^.*mac=((\w{2}:?)6}).*$)~~"};
    static const std::regex without_colons {R"~~((\w{2}):?)~~"}; 
    return std::regex_replace(
             std::regex_replace(s, mac_address, "$1"),
                 without_colons, "$1");
}
cigien
  • 57,834
  • 11
  • 73
  • 112