gpt4 book ai didi

c++ - 如何使用正则表达式从 C++ 字符串中提取字符串

转载 作者:行者123 更新时间:2023-11-30 01:29:28 24 4
gpt4 key购买 nike

我通过使用 #include <regex.h> 来使用正则表达式如果我有一个字符串 s,我如何使用正则表达式来搜索模式 p?

最佳答案

#include <regex.h>
#include <iostream>
#include <string>

std::string
match(const char *string, char *pattern)
{

// Adapted from:
http://pubs.opengroup.org/onlinepubs/009695399/functions/regcomp.html

int status;
regex_t re;
regmatch_t rm;


if (regcomp(&re, pattern, REG_EXTENDED) != 0) {
return "Bad pattern";
}
status = regexec(&re, string, 1, &rm, 0);
regfree(&re);
if (status != 0) {
return "No Match";
}
return std::string(string+rm.rm_so, string+rm.rm_eo);
}

int main(int ac, char **av) {
// e.g. usage: ./program abcdefg 'c.*f'
std::cout << match(av[1], av[2]) << "\n";
}

关于c++ - 如何使用正则表达式从 C++ 字符串中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5877267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com