【问题标题】:Regex result in one expresion正则表达式产生一个表达式
【发布时间】:2020-06-23 09:50:20
【问题描述】:

我有一个类似下面的示例字符串

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

从这个文本中我需要从中间提取mac地址,但中间没有分号。

我已经设法在 2 表达式中做到这一点,如下所示: (\w{2})[:](\w{2})[:](\w{2})[:](\w{2})[:](\w{2})[:](\w{2}) ==> 00:26:32:F0:83:B8

另一个/\W/ 应用于之前的结果 ==> 002632F083B8

但要求是仅在一个表达式中执行此操作。 是否有另一种方法可以在表达中做到这一点? 谢谢,

【问题讨论】:

  • 使用正则表达式 replace 方法。见regex101.com/r/w0IamZ/1。请注意,您不能在 1 个匹配操作中匹配不相交的文本片段。因此,您需要替换/匹配多个匹配项 + 连接。
  • 请告知您的编程环境
  • 我的编程语言是 C# 和 C++。如果无法实现一种表达方式,我会尝试这种方式。谢谢
  • 不,每个问题应该有一个,否则,它太宽泛了。这两个有很大的不同,请选择一个,并用失败的代码更新问题。

标签: c++ regex


【解决方案1】:

我不确定这是否满足您对单个表达式的要求

#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);
}

这是 2 个正则表达式,但更容易理解

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多