[英]C++ regex library
我有這個示例代碼
// regex_search example
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("eritueriotu3498 \"pi656\" sdfs3646df");
std::smatch m;
std::string reg("\\(?<=pi\\)\\(\\d+\\)\\(?=\"\\)");
std::regex e (reg);
std::cout << "Target sequence: " << s << std::endl;
std::cout << "The following matches and submatches were found:" << std::endl;
while (std::regex_search (s,m,e)) {
for (auto x:m) std::cout << x << " ";
std::cout << std::endl;
s = m.suffix().str();
}
return 0;
}
我需要獲取介於pi和“->(piMYNUMBER”)之間的數字。在在線正則表達式服務中,我的正則表達式工作正常(?<= pi)(\\ d +)(?=“),但c ++正則表達式不匹配任何內容。
誰知道我的表情出了什么問題? 最好的祝福
沒錯,C ++ std::regex
風格不支持lookbehinds。 您需要捕獲pi
和"
之間的數字:
#include <iostream>
#include <vector>
#include <regex>
int main() {
std::string s ("eritueriotu3498 \"pi656\" sdfs3646df");
std::smatch m;
std::string reg("pi(\\d+)\""); // Or, with a raw string literal:
// std::string reg(R"(pi(\d+)\")");
std::regex e (reg);
std::vector<std::string> results(std::sregex_token_iterator(s.begin(), s.end(), e, 1),
std::sregex_token_iterator());
// Demo printing the results:
std::cout << "Number of matches: " << results.size() << std::endl;
for( auto & p : results ) std::cout << p << std::endl;
return 0;
}
請參閱C ++演示 。 輸出:
Number of matches: 1
656
此處, pi(\\d+)"
模式匹配
pi
文字子字符串 (\\d+)
-將1個以上的數字捕獲到組1中 "
-使用雙引號。 注意std::sregex_token_iterator
的第四個參數,它是1
因為您只需要收集組1的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.