[英]How to get the ranges of all the non-matches in the string by regex?
我有一个正则表达式和一个字符串。 我需要找到字符串中所有不匹配的内容都是正则表达式,并获取字符串中的范围。 我怎样才能做到这一点?
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.