C++正则表达式

【2024|第15代版本Linux C/C++全栈开发合集(职场常用/面试常问技术点+项目实战)】

C++11引入了正则表达式支持,使得C++标准库可以处理字符串模式匹配和搜索。C++标准库中的正则表达式功能集中在<regex>头文件中,主要包含以下几个核心类和函数:

核心类和函数

  1. std::regex:表示一个正则表达式对象,用于模式匹配。
  2. std::smatchstd::cmatch:分别用于存储字符串(std::string)和C风格字符串(const char*)的匹配结果。
  3. std::regex_search:在输入序列中搜索正则表达式的匹配。
  4. std::regex_match:检测整个输入序列是否匹配正则表达式。
  5. std::regex_replace:使用正则表达式替换输入序列中的子字符串。

常用方法和用法

1. std::regex

正则表达式的定义和使用:

#include <iostream>
#include <regex>

int main() {
   
   
    std::string pattern = R"(\d+)";
    std::regex re(pattern);
    return 0;
}

R"(\d+)" 是一个原始字符串文字,避免了反斜杠转义的问题。

2. std::regex_match

用于检查整个字符串是否匹配给定的正则表达式:

#include <iostream>
#include <regex>

int main() {
   
   
    std::string s = "12345";
    std::regex re(R"(\d+)");
    
    if (std::regex_match(s, re)) {
   
   
        std::cout << "The entire string is a number.\n";
    } else {
   
   
        std::cout << "The string is not a number.\n";
    }

    return 0;
}
3. std::regex_search

用于在字符串中搜索正则表达式的匹配:

#include <iostream>
#include <regex>

int main() {
   
   
    std::string s = "Hello 123 World";
    std::regex re(R"(\d+)");
    std::smatch match;

    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值