简体   繁体   English

无法使用PCRE表达式的C ++正则表达式?

[英]C++ Regular Expression not Working w/ PCRE Expression?

I have the following code: 我有以下代码:

  include <regex>
  include <string>
  TCHAR basePath[MAX_PATH];
  GetCurrentDirectory(MAX_PATH, basePath);

  wstring test(&basePath[0]); //convert to wstring
  string test2(test.begin(), test.end()); //and convert to string.

  std::regex rBase("(.*my-dir)");
  std::smatch sm;
  std::regex_match(test2, sm, rBase);

However, sm always returns empty 但是,sm总是返回空

Basically if I have the following directory structure: 基本上,如果我具有以下目录结构:

E:\foo\bar\baz\my-dir\post1\dir2

I need to return 我要回去

"E:\foo\bar\baz\my-dir"

The regex seems to work if I run it though, say, python or javascript, but not here in C++ 如果我运行正则表达式似乎可以运行,例如python或javascript,但在C ++中却不能运行

What am I missing or what are some alternatives? 我想念的是什么?有什么选择?

Thanks 谢谢

std::regex_match checks whether the whole string matches the regex, not just any part of it. std::regex_match检查整个字符串是否与正则表达式匹配,而不仅仅是部分。

Use std::regex_search instead of std::regex_match or use a regex that matches the whole string, such as "(.*my-dir).*" , and extract the submatch with sm[1].str() . 使用std::regex_search而不是std::regex_match或使用匹配整个字符串的正则表达式,例如"(.*my-dir).*" ,然后使用sm[1].str()提取子匹配项。

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

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