第19章 正则表达式 - C++

2023-12-13 05:06:58

第19.1节 介绍

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

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

第19.2节 主类

这些类封装正则表达式和在字符的目标序列中匹配正则表达式的结果。

basic_regex(C++11)正则表达式对象
sub_match(C++11)标识子表达式所匹配的字符序列
match_results(C++11)标识一个正则表达式匹配,包含所有子表达式匹配

第19.3节 算法

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

regex_match(C++11)尝试匹配一个正则表达式到整个字符序列
regex_search(C++11)尝试匹配一个正则表达式到字符序列的任何部分
regex_replace(C++11)以格式化的替换文本来替换正则表达式匹配的出现位置

第19.4节 迭代器

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

regex_iterator(C++11)迭代一个字符序列中的所有正则表达式匹配
regex_token_iterator(C++11)迭代给定字符串中的所有正则表达式匹配中的指定子表达式,或迭代未匹配的子字符串

第19.5节 异常

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

regex_error(C++11)报告正则表达式库生成的错误

第19.5节 常量

在命名空间 std::regex_constants 定义

syntax_option_type(C++11)控制正则表达式行为的通用选项
match_flag_type(C++11)特定于匹配的选项
error_type(C++11)描述不同类型的匹配错误

第19.6节 案例

  1. 代码
#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("(\\w+)");
    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';
}
  1. 输出
Text contains the phrase 'regular expressions'
Found 20 words
Words longer than 6 characters:
  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].

文章来源:https://blog.csdn.net/qq_29086043/article/details/134817858
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。