我有一个正则表达式和一个字符串。我需要找到字符串中的所有不匹配项都是正则表达式,并获取字符串中的范围。
我怎样才能做到这一点?
#include <regex>
#include <string>
#include <iostream>
void printNonMatches(const std::regex& re, const std::string& str) {
const std::string& part;
size_t start;
size_t end;
/* get next non-match */
/* std::cout << part << " : " << start << ", " << end << std::endl; */
}
最佳答案
解:
#include <string>
#include <iostream>
#include <regex>
void printNonMatches(const std::regex& r, const std::string& s) {
size_t lastEndPosition = 0;
for (std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r); i != std::sregex_iterator(); ++i) {
std::smatch m = *i;
std::cout << s.substr(lastEndPosition, m.position() - lastEndPosition) << " : " << lastEndPosition << ", " << m.position() << std::endl;
lastEndPosition = m.position() + m.length();
}
if (lastEndPosition != s.length())
std::cout << s.substr(lastEndPosition, s.length() - lastEndPosition) << " : " << lastEndPosition << ", " << s.length() << std::endl;
}
int main() {
std::string s = "My new string";
std::regex r("\\s+");
printNonMatches(r, s);
return 0;
}
居住在ideone.com
关于c++ - 如何通过正则表达式获取字符串中所有不匹配的范围?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35451465/