且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

string :: find的C ++ regex等效

更新时间:2023-02-26 20:30:35

您可以使用以下C ++代码:

You may leverage the following C++ code:

#include <iostream>
#include <regex>
using namespace std;

int main() {
    std::string pattern("A|D");         // Regex expression
    std::regex rx(pattern);             // Getting the regex object 

    std::string s("ABCDEABCABD");       // Defining the string input
    std::ptrdiff_t number_of_matches = std::distance(  // Count the number of matches inside the iterator
        std::sregex_iterator(s.begin(), s.end(), rx),
        std::sregex_iterator());

    std::cout << number_of_matches << std::endl;  // Displaying results
    return 0;
}

请参阅 IDEONE demo

请注意:


  • 如果pattern可以包含具有特殊字符的文字字符,则可能需要转义。

  • std :: distance 返回第一个$