在C++中使用Boost正则表达式提取子匹配项

13

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

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(); 
}
4个回答

19

使用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 ...
}

也许我的正则表达式有问题,但对我来说这并没有产生正确的结果。 - John

17
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样式的正则表达式语法。还有其他可用的正则表达式语法。

0

0
boost::sub_match 转换为 std::string 最简单的方法是:
boost::smatch result;
// regex_search or regex_match ...
string s = result[1];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接