没有躲过的坑--正则表达式截取字符串
来源:互联网 发布:搜狗浏览器打开淘宝卡 编辑:程序博客网 时间:2024/06/17 04:13
工程中,需要从字符串中匹配出以:开头,并以:结束的字符串。
Google还是百度,很多C++的正则表达式都是通过st::tr1或boost库中使用的,但是我们仅仅用一个小小的功能,就用一个库不是很好的办法。
对的,之前我的博客已经介绍了C++11的新特性-正则表达式。
所以可以不使用其他的库,来完成任务:
std::vector<string> all_sub_string = {};std::string all_string = "12:wo:sfd:wom::sdf";std::regex e(":[a-z0-9_+-]+:");//正则规则const std::sregex_token_iterator end;for (std::sregex_token_iterator i(all_string .begin(), all_string .end(), e); i != end; ++i){ all_sub_string .push_back(*i);}
你可能会迷惑,什么是sregex_token_iterator?
不要着急,sregex_token_iterator其实就是字符串 regex_token_iterator 的类型定义。
typedef regex_token_iterator<string::const_iterator> sregex_token_iterator;
上面的方法很简单,就像使用迭代器一样。
其实regex还有其他的查找方法,现在介绍一下regex_search:
Returns whether some sub-sequence in the target sequence (the subject) matches the regular expression rgx (the pattern). The target sequence is either s or the character sequence between first and last, depending on the version used.
直接上代码:
// regex_search example#include <iostream>#include <string>#include <regex>int main (){ std::string s ("this subject has a submarine as a subsequence"); std::smatch m; std::regex e ("\\b(sub)([^ ]*)"); // matches words beginning by "sub" std::cout << "Target sequence: " << s << std::endl; std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl; std::cout << "The following matches and submatches were found:" << std::endl; while (std::regex_search (s,m,e)) { for (auto x:m) std::cout << x << " "; std::cout << std::endl; s = m.suffix().str(); } return 0;}
输出:
Target sequence: this subject has a submarine as subsequenceRegular expression: /\b(sub)([^ ]*)/The following matches and submatches were found:subject sub jectsubmarine sub marinesubsequence sub sequence
10 0
- 没有躲过的坑--正则表达式截取字符串
- 正则表达式截取字符串
- 正则表达式截取字符串
- 正则表达式截取字符串
- 没有躲过的坑--deprecated关键字
- 没有躲过的坑--智能指针陷阱
- 没有躲过的坑--重定义关键字
- 没有躲过的坑--std::string初始化、最快速判断字符串为空
- 通过正则表达式截取字符串
- 用正则表达式截取字符串
- java正则表达式截取字符串
- 没有躲过的坑--没有及时break出for循环
- ASP使用正则表达式截取字符串的func
- mysql字符串查找截取与正则表达式的联合应用
- js截取两个字符串之间的内容(正则表达式).
- 正则表达式截取字符串两字符间的内容
- 正则表达式-字符串基本的匹配,拆分,替换和截取
- Java利用正则表达式截取指定字符串之间的内容
- 控制流
- 当你输入一个网址后回车,实际会发生什么?
- 我的彩票界面
- 源码阅读笔记
- 非主流自然语言处理——遗忘算法系列(二):大规模语料词库生成
- 没有躲过的坑--正则表达式截取字符串
- [转]iOS isa 浅析
- Poj 352 UVA oj 1395 Slim Span 最小生成树应用
- java集合类ArrayList
- DICOM:DICOM3.0网络通信协议(三)
- mybatis 一对多
- 使用(x&y) + ((x^y)>>1) 求平均数
- JSON 之FastJson解析
- 南大软院大神养成计划--HTML和CSS基础课程(四)