判断字符串是否包含正则表达式默认的特殊字符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.
相关推荐
@老蝴7 小时前
Java EE - 线程安全的产生及解决方法
java·开发语言·java-ee
没有bug.的程序员8 小时前
Spring Cloud Alibaba 生态总览
java·开发语言·spring boot·spring cloud·alibaba
快乐非自愿9 小时前
Java垃圾收集器全解:从Serial到G1的进化之旅
java·开发语言·python
树在风中摇曳9 小时前
Java 静态成员与继承封装实战:从报错到彻底吃透核心特性
java·开发语言
芳草萋萋鹦鹉洲哦11 小时前
【Windows】tauri+rust运行打包工具链安装
开发语言·windows·rust
权泽谦11 小时前
R Shiny 交互式网页实战:从零到上线可视化应用
开发语言·信息可视化·r语言
hweiyu0012 小时前
Go Fiber 简介
开发语言·后端·golang
Molesidy13 小时前
【VSCode】【Clangd】Win下的基于LLVM/Clangd+Clangd插件+MINGW+CMake的VSCode配置C/C++开发环境的详细教程
c++·ide·vscode·clangd·llvm
ᐇ95914 小时前
Java LinkedList集合全面解析:双向链表的艺术与实战
java·开发语言·链表
码银14 小时前
【数据结构】顺序表
java·开发语言·数据结构