判断字符串是否包含正则表达式默认的特殊字符c++

判断字符串是否包含正则表达式默认的特殊字符

业务描述:

上层配置的字符列表中,既有准确的字符串,又有可以进行正则匹配的字符串,这时候需要区分出来那些是正则匹配的字符串。

思路:

判断字符串中,是否存在正则表达式默认的特殊字符,如*^${}等。

代码:

cpp 复制代码
#include <iostream>
#include <regex>

using namespace std;

// check if code contains regex special chars:*$^+?\{}|
static const string regexLimit = {".*[*$^+?\\\\{}|]+.*"};
static const std::regex pattern(regexLimit);
bool isRegex(const std::string& str) {
    try {
        return std::regex_match(str, pattern);
    }
    catch(const std::exception& e) {
        std::cout << "regex error:" << e.what() << endl;
        return false;
    }
}

int main(int argc, char const *argv[])
{
    std::cout<< "hello world!" << std::endl;

    string temp1 = "*demo.*";
    string temp2 = "^com.*.demo.*";
    string temp3 = "car$";
    string temp4 = "com.d+dmode";
    string temp5 = "com.d?dmode";
    string temp6 = "com.d\\dmode";
    string temp7 = "com.d{dmode";
    string temp8 = "com.d}dmode";
    string temp9 = "com.d|dmode";
    string temp41 = "com.demo.test";
    vector<std::string> list;
    list.push_back(temp1);
    list.push_back(temp2);
    list.push_back(temp3);
    list.push_back(temp4);
    list.push_back(temp5);
    list.push_back(temp6);
    list.push_back(temp7);
    list.push_back(temp8);
    list.push_back(temp9);
    
    list.push_back(temp41);
    for (size_t i = 0; i < list.size(); i++)
    {
        bool result = isRegex(list[i]);
        printf("i:%ld isRegex?:%d\n", i, result);
    }

    printf("hello world end.");
    return 0;
}

输出:

cpp 复制代码
hello world!
i:0 isRegex?:1
i:1 isRegex?:1
i:2 isRegex?:1
i:3 isRegex?:1
i:4 isRegex?:1
i:5 isRegex?:1
i:6 isRegex?:1
i:7 isRegex?:1
i:8 isRegex?:1
i:9 isRegex?:0
hello world end.
相关推荐
秋空樱雨2 分钟前
C++入门
开发语言·c++
咬_咬22 分钟前
C++仿mudo库高并发服务器项目:Buffer模块
服务器·开发语言·c++·缓冲区·buffer·muduo库
江公望28 分钟前
Qt qmlplugindump浅谈
开发语言·qt·qml
曦樂~30 分钟前
【Qt】文件操作/事件--mainwindow做编辑器
开发语言·qt
敲代码的瓦龙36 分钟前
西邮移动应用开发实验室2025年二面题解
开发语言·c++·算法
laocooon52385788637 分钟前
一个适合新手的训练C题
c语言·开发语言
C嘎嘎嵌入式开发1 小时前
(21)100天python从入门到拿捏《XML 数据解析》
xml·开发语言·python
晚风残1 小时前
【C++ Primer】第十七章:标准库特殊设施
开发语言·c++
神龙斗士2401 小时前
继承和组合
java·开发语言
一点七加一1 小时前
Harmony鸿蒙开发0基础入门到精通Day01--JavaScript篇
开发语言·javascript·华为·typescript·ecmascript·harmonyos