Som*_*ude 27 c++ regex gcc g++
我正在尝试使用正则表达式来尝试回答这个问题,并发现虽然regex_match
找到匹配,regex_search
却没有.
以下程序是用g ++ 4.7.1编译的:
#include <regex>
#include <iostream>
int main()
{
const std::string s = "/home/toto/FILE_mysymbol_EVENT.DAT";
std::regex rgx(".*FILE_(.+)_EVENT\\.DAT.*");
std::smatch match;
if (std::regex_match(s.begin(), s.end(), rgx))
std::cout << "regex_match: match\n";
else
std::cout << "regex_match: no match\n";
if (std::regex_search(s.begin(), s.end(), match, rgx))
std::cout << "regex_search: match\n";
else
std::cout << "regex_search: no match\n";
}
Run Code Online (Sandbox Code Playgroud)
输出:
regex_match: match regex_search: no match
我的假设是两者都应该匹配错误,或者GCC 4.7.1中的库可能存在问题吗?
你的正则表达式在VS 2012rc中运行正常(两者都匹配,这是正确的).
在g ++ 4.7.1中(-std=gnu++11)
,如果使用:
".*FILE_(.+)_EVENT\\.DAT.*"
,regex_match
匹配,但regex_search
没有.".*?FILE_(.+?)_EVENT\\.DAT.*"
既不匹配regex_match
也不regex_search
匹配(O_o).所有变体都应该匹配,但有些变量不匹配(原因已经被betabandido指出).在g ++ 4.6.3中(-std=gnu++0x)
,行为与g ++ 4.7.1相同.
Boost(1.50)正确匹配所有两种模式.
摘要:
regex_match regex_search ----------------------------------------------------- g++ 4.6.3 linux OK/- - g++ 4.7.1 linux OK/- - vs 2010 OK OK vs 2012rc OK OK boost 1.50 win OK OK boost 1.50 linux OK OK -----------------------------------------------------
关于你的模式,如果你的意思是一个点字符'.'
,那么你应该写so("\\."
).您还可以通过使用非贪婪修饰符(?
)来减少回溯:
".*?FILE_(.+?)_EVENT\\.DAT.*"
Run Code Online (Sandbox Code Playgroud)
假设C++和Boost Regex具有相似的结构和功能,这里解释regex_match
和之间的区别:regex_search
该
regex_match()
如果正则表达式的整个输入匹配,从开始到结束算法将只报告成功.如果正则表达式只匹配输入的一部分,regex_match()
则返回false.如果要搜索字符串以查找正则表达式匹配的子字符串,请使用该regex_search()
算法.