簡體   English   中英

C ++使用Regex查找子字符串

[英]C++ Use Regex to find substring

我有一個字符串測試

<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 e ("<a href=.*?>"); cmatch =cm; 標記我要查找的子字符串。

我下一步該怎么做?

我使用regex_match(htmlString, cm, e); 使用htmlString作為wchar_t*

如果要查找所有匹配的子字符串,則需要使用regex迭代器:

// 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';
    }
}

這將匹配完整a標簽,並獲得href屬性值,
在捕獲組2中。

應該這樣做,因為href屬性可以位於標記中的任何位置。

<a(?=(?:[^>"']|"[^"]*"|'[^']*')*?\\shref\\s*=\\s*(?:(['"])([\\S\\s]*?)\\1))\\s+(?:"[\\S\\s]*?"|'[\\S\\s]*?'|[^>]*?)+>

您可以用[\\w:}+代替a標簽,以獲取所有標簽的href

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

格式化並測試

 < 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]*? ' | [^>]*? )+
 >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM