在c++中使用boost regex提取子匹配
Extracting submatches using boost regex in c++
我试图使用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];
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么istream不支持右值提取
- 此模式的C++RegEx
- 如何设置一个范围来提取我想要获得的信息
- 视觉工作室项目.提取源文件夹名称
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 使用 c++/boost::regex 提取 HTML 文件的特定部分
- Regex,用于从C++代码中提取函数
- 在 C++Builder 中使用 boost::regex 提取双引号
- Regex无法从字符串中提取双参数子字符串
- Regex表达式提取括号内的所有内容
- c++ regex提取子字符串
- 在c++中使用boost regex提取子匹配
- Regex:C++提取双引号内的文本
- Regex C++:提取标记之间的子字符串
- 从std::regex中提取原始regex模式