[C/C++11]_[初级]_[使用正则表达式分组来获取动态字符串]
场景
- 之前使用
Objective-C
获取所有的分组[1], 只不过ObjC
只能在macOS
上使用。如果是在Windows
上,可以使用C++11
标准库的正则库来进行分组。 如果是跨平台实现,可以使用utf-8
编码。
说明
-
C++11
的正则查找第一个分组字符串,可以使用regex_search
函数。 如果需要遍历字符串里的所有分组,那么需要创建sregex_iterator
枚举变量。 -
注意,如果是要给字符串里的
click here
加超链接样式。
-
Windows
创建CLinkCtrl
时,需要给字符串加上<a href=''>xx</a>
才会有超链接效果。使用matches.position(i)
来获取字符串的位置,创建一个新的string
,并通过append
方法来组合其他字符串和分组字符串来形成新的字符串。string str; ... str.append("<a href='https://'").append(matches[i]).append("</a>");
-
macOS
的Cocoa
是通过创建分组字符串的NSAttributedString*
来封装分组字符串matches[i]
。
例子
#include <iostream>
#include <regex>
#include <string>using namespace std;void TestSearchFirstGroup(const string& text,const char* pattern1)
{regex pattern(pattern1);smatch matches;if (!regex_search(text, matches, pattern))return;for (int i = 0; i < matches.size(); i++){if (i) {cout << "Group str is: " << matches[i] << "-> position: " << matches.position(i) << endl;}//else {// cout << "Whole Group str is: " << matches[i] << endl;//}}
}void TestSearchAllGroup(const string& text,const char* pattern1)
{regex pattern(pattern1);auto begin = std::sregex_iterator(text.begin(), text.end(), pattern);auto end = std::sregex_iterator();for (std::sregex_iterator i = begin; i != end; ++i) {std::smatch matches = *i;for (int i = 0; i < matches.size(); i++){if (i) {cout << "Group str is: " << matches[i] << "-> position: " << matches.position(i) << endl;}//else {// cout << "Whole Group str is: " << match[i] << endl;//}}}}int main()
{ cout << "========== TestSearchFirstGroup =============" << endl;TestSearchFirstGroup("Please |click here$ to erase all system |settings$ and data.","[|]([^|$]+)[$]");cout << "========== TestSearchGroup2 =============" << endl;TestSearchAllGroup("Please |click here$ to erase all system |settings$ and data.","[|]([^|$]+)[$]");return 0;
}
输出
========== TestSearchFirstGroup =============
Group str is: click here-> position: 8
========== TestSearchGroup2 =============
Group str is: click here-> position: 8
Group str is: settings-> position: 41
参考
-
使用正则表达式分组来获取动态字符串
-
使用正则表达式库进行分组查询
-
std::regex_search
-
std::regex_iterator
-
std::match_results