简体   繁体   English

C ++正则表达式库

[英]C++ regex library

I have this sample code 我有这个示例代码

// 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;
}

I need to get number between pi and " -> (piMYNUMBER") In online regex service my regex works fine (?<=pi)(\\d+)(?=") but c++ regex don't match anything. 我需要获取介于pi和“->(piMYNUMBER”)之间的数字。在在线正则表达式服务中,我的正则表达式工作正常(?<= pi)(\\ d +)(?=“),但c ++正则表达式不匹配任何内容。

Who knows what is wrong with my expression? 谁知道我的表情出了什么问题? Best regards 最好的祝福

That is correct, C++ std::regex flavors do not support lookbehinds. 没错,C ++ std::regex风格不支持lookbehinds。 You need to capture the digits between pi and " : 您需要捕获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;
}

See the C++ demo . 请参阅C ++演示 Output: 输出:

Number of matches: 1
656

Here, pi(\\d+)" pattern matches 此处, pi(\\d+)"模式匹配

  • pi - a literal substring pi文字子字符串
  • (\\d+) - captures 1+ digits into Group 1 (\\d+) -将1个以上的数字捕获到组1中
  • " - consumes a double quote. " -使用双引号。

Note the fourth argument to std::sregex_token_iterator , it is 1 because you need to collect only Group 1 values. 注意std::sregex_token_iterator的第四个参数,它是1因为您只需要收集组1的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM