【问题标题】:C++ Use Regex to find substringC++ 使用正则表达式查找子字符串
【发布时间】:2017-12-21 16:14:06
【问题描述】:

我有一个字符串测试

<td><a href="4.%20Functions,%20scope.ppt">4. Functions, scope.ppt</a></td>

我想找到<a href="4.%20Functions,%20scope.ppt">(作为子字符串)

使用 Dr.Google 进行搜索:regex e ("<a href=.*?>"); cmatch =cm; 以标记我要查找的子字符串。

接下来我该怎么做?

我可以使用regex_match(htmlString, cm, e);htmlString 作为wchar_t*

【问题讨论】:

  • “接下来我该怎么做?”是什么意思?是否要查找 所有 匹配的子字符串?
  • 向 Google 博士寻求治疗方法。
  • 为什么 wchat_t 而不仅仅是 char?
  • 要匹配一个精确的字符串,您不需要正则表达式。

标签: c++ regex


【解决方案1】:

如果你想找到 all 匹配的子字符串,那么你需要使用正则表达式迭代器:

// example data
std::wstring const html = LR"(

<td><a href="4.%20Functions,%20scope.ppt">4. Functions, scope.ppt</a></td>
<td><a href="4.%20Functions,%20scope.ppt">4. Functions, scope.ppt</a></td>
<td><a href="4.%20Functions,%20scope.ppt">4. Functions, scope.ppt</a></td>

)";

// for convenience
constexpr auto fast_n_loose = std::regex_constants::optimize|std::regex_constants::icase;

// extract href's
std::wregex const e_link{LR"~(href=(["'])(.*?)\1)~", fast_n_loose};

int main()
{
    // regex iterators       
    std::wsregex_iterator itr_end;
    std::wsregex_iterator itr{std::begin(html), std::end(html), e_link};

    // iterate through the matches
    for(; itr != itr_end; ++itr)
    {
        std::wcout << itr->str(2) << L'\n';
    }
}

【讨论】:

  • 如果我理解问题 +1,这似乎正是 OP 正在寻找的内容。
  • 我可以用string代替wstring吗?
  • @BUICHAUMinhTung 您的问题提到了wchar_t* 的数据,因此您确实需要为此使用std::wstring。但是,如果您不需要处理多字节字符,您可以使用 std::stringstd::regexstd::sregex_iterator 完成所有这些操作。
  • @BUICHAUMinhTung 如果您的源数据是UTF-8 中的std::string,那么您需要转换为宽字符unicode,如此答案stackoverflow.com/questions/37989081/… 中的示例转换函数可以在此答案中找到: stackoverflow.com/questions/43302279/…
【解决方案2】:

这将匹配完整的a标签,并获得href属性值,
在捕获组 2 中。

应该这样做,因为 href 属性可以在标签中的任何位置。

&lt;a(?=(?:[^&gt;"']|"[^"]*"|'[^']*')*?\shref\s*=\s*(?:(['"])([\S\s]*?)\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^&gt;]*?)+&gt;

您可以用[\w:}+ 代替a 标签来从所有标签中获取href

https://regex101.com/r/LHZXUM/1

Formatted and tested

 < a                    # a tag, substitute [\w:]+ for any tag

 (?=                    # Asserttion (a pseudo atomic group)
      (?: [^>"'] | " [^"]* " | ' [^']* ' )*?
      \s href \s* = \s* 
      (?:
           ( ['"] )               # (1), Quote
           ( [\S\s]*? )           # (2), href value
           \1 
      )
 )
 \s+ 
 (?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*? )+
 >

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2016-05-16
    • 2012-05-12
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多