【C++11】正则表达式库

简介

定义于头文件<regex>

正则表达式库提供表示正则表达的类,正则表达式是一种用于在字符串中匹配模式的微型语言。下列数种对象上的操作能刻画几乎所有带正则表达式的操作:

  • 目标序列。为模式而搜索到的字符序列。这可以是二个迭代器所指定的范围、空终止字符串或一个 std::string
  • 模式。这是正则表达式自身。它确定构成匹配者。它是从带特定语法的字符串构成的 std::basic_regex 类型对象。受支持的语法变体的描述见 syntax_option_type
  • 匹配的数组。关于匹配的信息可作为 std::match_results 类型对象获取。
  • 替换字符串。这是确定如何替换匹配的字符串,受支持的语法变体的描述见 match_flag_type

主类

类名备注
basic_regex正则表达式对象
sub_match标识子表达式所匹配的字符序列
match_results标识一个正则表达式匹配,包含所有子表达式匹配

算法

这些算法将封装于 regex 的正则表达式应用到字符的目标序列。

函数名备注
regex_match试图匹配正则表达式到整个字符序列
regex_search试图匹配正则表达式到字符序列的任何部分
regex_replace以格式化的替换文本来替换正则表达式匹配的出现位置

迭代器

regex_iterator 用于遍历在序列中找到的匹配正则表达式的整个集合。

类名备注
regex_iterator在字符序列中通过所有正则表达式匹配迭代
regex_token_iterator通过在给定的字符串中所有正则表达式匹配中的指定子表达式,或通过不匹配的子串迭代

异常

此类定义作为异常抛出以报告来自正则表达式库错误的类型。

类名备注
regex_error报告正则表达式库生成的错误

示例&输出

  • 实例
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
 
int main()
{
    std::string s = "Some people, when confronted with a problem, think "
        "\"I know, I'll use regular expressions.\" "
        "Now they have two problems.";
 
    std::regex self_regex("REGULAR EXPRESSIONS",
            std::regex_constants::ECMAScript | std::regex_constants::icase);
    if (std::regex_search(s, self_regex)) {
        std::cout << "Text contains the phrase 'regular expressions'\n";
    }
 
    std::regex word_regex("(\\S+)");
    auto words_begin = 
        std::sregex_iterator(s.begin(), s.end(), word_regex);
    auto words_end = std::sregex_iterator();
 
    std::cout << "Found "
              << std::distance(words_begin, words_end)
              << " words\n";
 
    const int N = 6;
    std::cout << "Words longer than " << N << " characters:\n";
    for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
        std::smatch match = *i;
        std::string match_str = match.str();
        if (match_str.size() > N) {
            std::cout << "  " << match_str << '\n';
        }
    }
 
    std::regex long_word_regex("(\\w{7,})");
    std::string new_s = std::regex_replace(s, long_word_regex, "[$&]");
    std::cout << new_s << '\n';
}
  • 输出

Text contains the phrase ‘regular expressions’
Found 19 words
Words longer than 6 characters:
people,
confronted
problem,
regular
expressions."
problems.
Some people, when [confronted] with a [problem], think
“I know, I’ll use [regular] [expressions].” Now they have two [problems].

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cout0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值