string :: find的C ++ regex等效 [英] C++ regex equivalent for string::find
问题描述
我试图编辑一个开源的C ++程序进行一个简单的调整,使其中一个输入接受一个regexp字符串而不是一个字符串。我是一个完整的C ++ noob(从来没有写任何东西)所以我希望有人可以指向我的一个函数,将工作。请使用以下代码:
I'm trying to edit an open source C++ program to make a simple adjustment so that one of the input's accepts a regexp string instead of a string. I'm a complete C++ noob (never written anything) so I'm hoping someone can point me to a function that will work. Take the following code:
#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)。
I would like 'pattern' to accept a regular expression of several patterns seperated by the pipe sign, eg 'A|D' (which would output 5 in this case).
根据我从此C ++引用页面,您不能像string :: find函数那样提供正则表达式。
From what I gather from this C++ reference page, you cannot supply a regular expression like this to the string::find function. What function can I put here instead?
谢谢!
推荐答案
您可以使用以下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
是返回第一个$
这篇关于string :: find的C ++ regex等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!