[C/C++11]_[初级]_[使用正则表达式分组来获取动态字符串]

发布于:2025-06-24 ⋅ 阅读:(18) ⋅ 点赞:(0)

场景

  1. 之前使用Objective-C获取所有的分组[1], 只不过ObjC只能在macOS上使用。如果是在Windows上,可以使用C++11标准库的正则库来进行分组。 如果是跨平台实现,可以使用utf-8编码。

说明

  1. C++11的正则查找第一个分组字符串,可以使用regex_search函数。 如果需要遍历字符串里的所有分组,那么需要创建sregex_iterator枚举变量。

  2. 注意,如果是要给字符串里的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>");
    
  • macOSCocoa是通过创建分组字符串的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

参考

  1. 使用正则表达式分组来获取动态字符串

  2. 使用正则表达式库进行分组查询

  3. std::regex_search

  4. std::regex_iterator

  5. std::match_results


网站公告

今日签到

点亮在社区的每一天
去签到