【算法】C++中的正则表达式(一定程度上可代替KMP等)

简介

C++11中多了regex库,可用于正则表达式的各项操作。
这里以 P3167 [CQOI2014]通配符匹配 为例(但是要求字符串比较短,原题如果通过正则表达式做只能得30分,其余全是TLE)。

题目大意

给出一个带有通配符的字符串(在此字符串中,*所占据的位置可放置0及以上个字符,?占据的位置放且只能放1个字符),求给出n个字符串是否匹配这个通配符表达式。

#include <bits/stdc++.h>
#define int long long

using namespace std;

int n;
const int len = 10010;

string s, ss;

// 字符串替换函数: replace_str(字符串, 被替换字符串, 替换字符串)
void replace_str(string& str, const string& old_value, const string& new_value){
    for(string::size_type pos(0); pos != string::npos; pos += new_value.length()) {
        if((pos = str.find(old_value,pos)) != string::npos)
        str.replace(pos, old_value.length(), new_value);
    else break;
    }
}

// 对比是否匹配
void compare(string ss){
    regex reg(s);
    if(regex_match(ss, reg)) cout << "YES" << endl;
    else cout << "NO" << endl;
}

signed main(){
    cin >> s;
    cin >> n;
    int l = s.length();
    replace_str(s, "*", "[a-z0-9]*");
    replace_str(s, "?", "[a-z0-9]{1}");
    while(n--){
        cin >> ss;
        compare(ss);
    }
    return 0;
}

针对题目给出的样例:

*aca?ctc
6
acaacatctc
acatctc
aacacatctc
aggggcaacacctc
aggggcaacatctc
aggggcaacctct

输出:

YES
YES
YES
YES
YES
NO

参考资料

[1] 正则表达式 - 教程_菜鸟教程
[2] C++正则表达式 - cpluspluser_博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值