判断字符串是否包含正则表达式默认的特殊字符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.
相关推荐
Villiam_AY2 小时前
Redis 缓存机制详解:原理、问题与最佳实践
开发语言·redis·后端
UQWRJ2 小时前
菜鸟教程R语言一二章阅读笔记
开发语言·笔记·r语言
岁忧4 小时前
macOS配置 GO语言环境
开发语言·macos·golang
朝朝又沐沐5 小时前
算法竞赛阶段二-数据结构(36)数据结构双向链表模拟实现
开发语言·数据结构·c++·算法·链表
魔尔助理顾问5 小时前
系统整理Python的循环语句和常用方法
开发语言·后端·python
Ares-Wang5 小时前
JavaScript》》JS》 Var、Let、Const 大总结
开发语言·前端·javascript
逝雪Yuki5 小时前
Leetcode——287. 寻找重复数
c++·leetcode·二分查找·双指针·环形链表
遇见尚硅谷6 小时前
C语言:*p++与p++有何区别
c语言·开发语言·笔记·学习·算法
SkyrimCitadelValinor6 小时前
c#中让图片显示清晰
开发语言·c#
艾莉丝努力练剑6 小时前
【数据结构与算法】数据结构初阶:详解排序(二)——交换排序中的快速排序
c语言·开发语言·数据结构·学习·算法·链表·排序算法