我正在尝试编辑开放源代码C ++程序以进行简单调整,以使输入的其中一个接受正则表达式字符串而不是字符串。我是一个完整的C ++新手(从来没有写过任何东西),所以我希望有人可以指出我想要的功能。采取以下代码:
#include <iostream>
#include <string>
int main() {
std::string str1("ABCDEABCABD");
std::string pattern("A");
int count1 = 0;
size_t p1 = str1.find(pattern, 0);
while(p1 != std::string::npos)
{
p1 = str1.find(pattern,p1+pattern.size());
count1 += 1;
}
std::cout << count1 << std::endl;
}
我希望'pattern'接受由管道符号分隔的多个模式的正则表达式,例如'A | D'(在这种情况下将输出5)。
根据我从C ++参考页上收集的信息,您无法向string :: find函数提供这样的正则表达式。我可以在这里放什么功能呢?
谢谢!
您可以利用以下C ++代码:
#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;
}
注意:
std::distance
是一个函数,该函数返回first
和之间last
的元素数量,迭代器产生的元素数量。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句