在c++中使用boost regex提取子匹配

Extracting submatches using boost regex in c++

本文关键字:提取 regex boost c++      更新时间:2023-10-16

我试图使用boost regex从文本文件中提取子匹配。目前,我只返回第一行和完整的行,而不是有效的电子邮件地址。我尝试使用迭代器和子匹配,但我没有成功。下面是当前代码:

if(Myfile.is_open()) {
    boost::regex pattern("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$");
    while(getline(Myfile, line)) {
            string::const_iterator start = line.begin();
            string::const_iterator end = line.end();
            boost::sregex_token_iterator i(start, end, pattern);
            boost::sregex_token_iterator j;
            while ( i != j) {
            cout << *i++ << endl;  
    } 
    Myfile.close(); 
}

使用boost::smatch.

boost::regex pattern("what(ever) ...");
boost::smatch result;
if (boost::regex_search(s, result, pattern)) {
    string submatch(result[1].first, result[1].second);
    // Do whatever ...
}
const string pattern = "(abc)(def)";  
const string target = "abcdef"; 
boost::regex regexPattern(pattern, boost::regex::extended); 
boost::smatch what; 
bool isMatchFound = boost::regex_match(target, what, regexPattern); 
if (isMatchFound) 
{ 
    for (unsigned int i=0; i < what.size(); i++) 
    { 
        cout << "WHAT " << i << " " << what[i] << endl; 
    } 
} 

输出如下

WHAT 0 abcdef 
WHAT 1 abc 
WHAT 2 def 

Boost使用括号括起来的子匹配,并且第一个子匹配始终是完全匹配的字符串。Regex_match必须根据模式匹配整行输入,如果您试图匹配子字符串,请使用regex_search代替。

我上面使用的示例使用posix扩展正则表达式语法,它是使用boost::regex::extended参数指定的。省略该参数将改变语法,使用perl风格的正则表达式语法。可以使用其他regex语法

这一行:

string submatch(result[1].first, result[1].second);

在visual c++中导致错误(我对2012进行了测试,但预计更早的版本也会出现错误)

https://groups.google.com/forum/?fromgroups见!

boost::sub_match转换为std::string最简单的方法:

boost::smatch result;
// regex_search or regex_match ...
string s = result[1];