C++相关闲碎记录(16)

news2024/9/23 7:26:12

1、正则表达式

(1)regex的匹配和查找接口
#include <regex>
#include <iostream>
using namespace std;

void out (bool b)
{
    cout << ( b ? "found" : "not found") << endl;
}

int main()
{
    // find XML/HTML-tagged value (using default syntax):
    regex reg1("<.*>.*</.*>");
    bool found = regex_match ("<tag>value</tag>",   // data
                              reg1);                // regular expression
    out(found);
    
    // find XML/HTML-tagged value (tags before and after the value must match):
    regex reg2("<(.*)>.*</\\1>");
    found = regex_match ("<tag>value</tag>",        // data
                         reg2);                     // regular expression
    out(found);

    // find XML/HTML-tagged value (using grep syntax):
    regex reg3("<\\(.*\\)>.*</\\1>",regex_constants::grep);
    found = regex_match ("<tag>value</tag>",        // data
                         reg3);                     // regular expression
    out(found);

    // use C-string as regular expression (needs explicit cast to regex):
    found = regex_match ("<tag>value</tag>",        // data
                         regex("<(.*)>.*</\\1>"));  // regular expression
    out(found);
    cout << endl;

    // regex_match() versus regex_search():
    found = regex_match ("XML tag: <tag>value</tag>", 
                         regex("<(.*)>.*</\\1>"));         // fails to match
    out(found);
    found = regex_match ("XML tag: <tag>value</tag>", 
                         regex(".*<(.*)>.*</\\1>.*"));     // matches
    out(found);
    found = regex_search ("XML tag: <tag>value</tag>", 
                          regex("<(.*)>.*</\\1>"));        // matches
    out(found);
    found = regex_search ("XML tag: <tag>value</tag>", 
                          regex(".*<(.*)>.*</\\1>.*"));    // matches
    out(found);
}
输出:
found
found
found
found

not found
found
found
found

regex_match()检验是否整个字符序列匹配某个正则表达式。

regex_search()检验是否部分字符序列匹配某个正则表达式。

regex_match(data, regex(pattern))

总是等价于

regex_search(data, regex("(.|\n)*" + pattern + "(.|\n)*")),其中(.|\n)*指任何数量和任意字符,.意指换行之外的任意字符,|表示or。

(2)处理次表达式
#include <string>
#include <regex>
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    string data = "XML tag: <tag-name>the value</tag-name>.";
    cout << "data:             " << data << "\n\n";

    smatch m;  // for returned details of the match
    bool found = regex_search (data,
                               m, 
                               regex("<(.*)>(.*)</(\\1)>"));  //出现\1则是代表与第一个小括号中要匹配的内容相同。

    // print match details:
    cout << "m.empty():        " << boolalpha << m.empty() << endl;
    cout << "m.size():         " << m.size() << endl;
    if (found) {
        cout << "m.str():          " << m.str() << endl;
        cout << "m.length():       " << m.length() << endl;
        cout << "m.position():     " << m.position() << endl;
        cout << "m.prefix().str(): " << m.prefix().str() << endl;
        cout << "m.suffix().str(): " << m.suffix().str() << endl;
        cout << endl;

        // iterating over all matches (using the match index):
        for (int i=0; i<m.size(); ++i) {
            cout << "m[" << i << "].str():       " << m[i].str() << endl;
            cout << "m.str(" << i << "):         " << m.str(i) << endl;
            cout << "m.position(" << i << "):    " << m.position(i)
                 << endl;
        }
        cout << endl;

        // iterating over all matches (using iterators):
        cout << "matches:" << endl;
        for (auto pos = m.begin(); pos != m.end(); ++pos) {
            cout << " " << *pos << " ";
            cout << "(length: " << pos->length() << ")" << endl;
        }
    }
}
输出:
data:             XML tag: <tag-name>the value</tag-name>.

m.empty():        false
m.size():         4
m.str():          <tag-name>the value</tag-name>
m.length():       30
m.position():     9
m.prefix().str(): XML tag:
m.suffix().str(): .

m[0].str():       <tag-name>the value</tag-name>
m.str(0):         <tag-name>the value</tag-name>
m.position(0):    9
m[1].str():       tag-name
m.str(1):         tag-name
m.position(1):    10
m[2].str():       the value
m.str(2):         the value
m.position(2):    19
m[3].str():       tag-name
m.str(3):         tag-name
m.position(3):    30

matches:
 <tag-name>the value</tag-name> (length: 30)
 tag-name (length: 8)
 the value (length: 9)
 tag-name (length: 8)

smatch:针对“匹配string”而设计

cmatch:针对“匹配C-string(const char*)”而设计

wsmatch:针对“匹配wstring”而设计

wcmatch:针对“匹配wide C-string(const wchar_t*)”而设计

出现\1则是代表与第一个小括号中要匹配的内容相同。注意:\1必须与小括号配合使用

 (3)regex iterator
#include <string>
#include <regex>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    string data = "<person>\n"
                  " <first>Nico</first>\n"
                  " <last>Josuttis</last>\n"
                  "</person>\n";

    regex reg("<(.*)>(.*)</(\\1)>");

    // iterate over all matches (using a regex_iterator):
    sregex_iterator pos(data.cbegin(),data.cend(),reg);
    sregex_iterator end;
    for ( ; pos!=end ; ++pos ) {
        cout << "match:  " << pos->str() << endl;
        cout << " tag:   " << pos->str(1) << endl;
        cout << " value: " << pos->str(2) << endl;
    }

    // use a regex_iterator to process each matched substring as element in an algorithm:
    sregex_iterator beg(data.cbegin(),data.cend(),reg);
    for_each (beg,end,[](const smatch& m) {
                          cout << "match:  " << m.str() << endl;
                          cout << " tag:   " << m.str(1) << endl;
                          cout << " value: " << m.str(2) << endl;
                      });
}
输出:
match:  <first>Nico</first>
 tag:   first
 value: Nico
match:  <last>Josuttis</last>
 tag:   last
 value: Josuttis
match:  <first>Nico</first>
 tag:   first
 value: Nico
match:  <last>Josuttis</last>
 tag:   last
 value: Josuttis
(4)regex token iterator
#include <string>
#include <regex>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    string data = "<person>\n"
                  " <first>Nico</first>\n"
                  " <last>Josuttis</last>\n"
                  "</person>\n";

    regex reg("<(.*)>(.*)</(\\1)>");

    // iterate over all matches (using a regex_token_iterator):
    sregex_token_iterator pos(data.cbegin(),data.cend(), // sequence
                              reg,                       // token separator
                              {0,2});      // 0: full match, 2: second substring
    sregex_token_iterator end;
    for ( ; pos!=end ; ++pos ) {
        cout << "match:  " << pos->str() << endl;
    }
    cout << endl;

    string names = "nico, jim, helmut, paul, tim, john paul, rita";
    regex sep("[ \t\n]*[,;.][ \t\n]*");  // separated by , ; or . and spaces
    sregex_token_iterator p(names.cbegin(),names.cend(),  // sequence
                            sep,                          // separator
                            -1);        // -1: values between separators
    sregex_token_iterator e;
    for ( ; p!=e ; ++p ) {
        cout << "name:  " << *p << endl;
    }
}
输出:
match:  <first>Nico</first>
match:  Nico
match:  <last>Josuttis</last>
match:  Josuttis

name:  nico
name:  jim
name:  helmut
name:  paul
name:  tim
name:  john paul
name:  rita
(5)用于替换的正则表达式
#include <string>
#include <regex>
#include <iostream>
#include <iterator>

using namespace std;

int main() {
    string data = "<person>\n"
                  " <first>Nico</first>\n"
                  " <last>Josuttis</last>\n"
                  "</person>\n";
    regex reg("<(.*)>(.*)</(\\1)>");
    cout << regex_replace(data,
                          reg,                               
                          "<$1 value=\"$2\"/>") << endl;     //replacement
    cout << regex_replace(data,
                          reg,
                          "<\\1 value=\"\\2\"/>",
                           regex_constants::format_sed) << endl;
    string res2;
    regex_replace(back_inserter(res2),
                  data.begin(), data.end(),
                  reg,
                  "<$1 value=\"$2\"/>",
                  regex_constants::format_no_copy | regex_constants::format_first_only);
    cout << res2 << endl;
    return 0;
}
输出:
<person>
 <first value="Nico"/>
 <last value="Josuttis"/>
</person>

<person>
 <first value="Nico"/>
 <last value="Josuttis"/>
</person>

<first value="Nico"/>

(6)regex flag
#include <string>
#include <regex>
#include <iostream>
using namespace std;

int main()
{
    // case-insensitive find LaTeX index entries
    string pat1 = R"(\\.*index\{([^}]*)\})";       // first capture group
    string pat2 = R"(\\.*index\{(.*)\}\{(.*)\})";  // 2nd and 3rd capture group
    regex pat (pat1+"\n"+pat2,
               regex_constants::egrep|regex_constants::icase);

    // initialize string with characters from standard input:
    string data((istreambuf_iterator<char>(cin)),
                istreambuf_iterator<char>());

    // search and print matching index entries:
    smatch m;
    auto pos = data.cbegin();
    auto end = data.cend();
    for ( ; regex_search (pos,end,m,pat); pos=m.suffix().first) {
        cout << "match: " << m.str() << endl;
        cout << "  val: " << m.str(1)+m.str(2) << endl;
        cout << "  see: " << m.str(3) << endl;
    }
}

 (7)regex 异常
#include <regex>
#include <string>

template <typename T>
std::string regexCode (T code)
{
    switch (code) {
      case std::regex_constants::error_collate:
        return "error_collate: "
               "regex has invalid collating element name";
      case std::regex_constants::error_ctype:
        return "error_ctype: "
               "regex has invalid character class name";
      case std::regex_constants::error_escape:
        return "error_escape: "
               "regex has invalid escaped char. or trailing escape";
      case std::regex_constants::error_backref:
        return "error_backref: "
               "regex has invalid back reference";
      case std::regex_constants::error_brack:
        return "error_brack: "
               "regex has mismatched '[' and ']'";
      case std::regex_constants::error_paren:
        return "error_paren: "
               "regex has mismatched '(' and ')'";
      case std::regex_constants::error_brace:
        return "error_brace: "
               "regex has mismatched '{' and '}'";
      case std::regex_constants::error_badbrace:
        return "error_badbrace: "
               "regex has invalid range in {} expression";
      case std::regex_constants::error_range:
        return "error_range: "
               "regex has invalid character range, such as '[b-a]'";
      case std::regex_constants::error_space:
        return "error_space: "
               "insufficient memory to convert regex into finite state";
      case std::regex_constants::error_badrepeat:
        return "error_badrepeat: "
               "one of *?+{ not preceded by valid regex";
      case std::regex_constants::error_complexity:
        return "error_complexity: "
               "complexity of match against regex over pre-set level";
      case std::regex_constants::error_stack:
        return "error_stack: "
               "insufficient memory to determine regex match";
    }
    return "unknown/non-standard regex error code";
}
#include <regex>
#include <iostream>
#include "regexexception.hpp"
using namespace std;

int main()
{
  try {
    // initialize regular expression with invalid syntax:
    regex pat ("\\\\.*index\\{([^}]*)\\}",
               regex_constants::grep|regex_constants::icase);
    //...
  }
  catch (const regex_error& e) {
        cerr << "regex_error: \n"
             << " what(): " << e.what() << "\n"
             << " code(): " << regexCode(e.code()) << endl;
  }
}
(8)regex ECMAScript文法

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1315931.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++干货铺】继承后的多态 | 抽象类

个人主页点击直达&#xff1a;小白不是程序媛 C系列专栏&#xff1a;C干货铺 代码仓库&#xff1a;Gitee 目录 多态的概念 多态的定义和实现 多态的定义条件 虚函数 虚函数的重写 特殊情况 协变&#xff08;基类和派生类的虚函数返回值不同&#xff09; 析构函数的重…

如果你找不到东西,请先确保你在正确的地方寻找

之前我们在几篇文章中描述了如何进行”思想”调试&#xff0c;今天的文章我将不会这样做。 因为下面的编程错误大部分人都会遇到&#xff0c;如果你看一眼下面的代码&#xff0c;你不会发现有什么问题&#xff0c;这仅仅是因为你的的大脑只给你希望看到的&#xff0c;而不是那…

分数约分-第11届蓝桥杯选拔赛Python真题精选

[导读]&#xff1a;超平老师的Scratch蓝桥杯真题解读系列在推出之后&#xff0c;受到了广大老师和家长的好评&#xff0c;非常感谢各位的认可和厚爱。作为回馈&#xff0c;超平老师计划推出《Python蓝桥杯真题解析100讲》&#xff0c;这是解读系列的第20讲。 分数约分&#xf…

算法模板之单链表图文讲解

&#x1f308;个人主页&#xff1a;聆风吟 &#x1f525;系列专栏&#xff1a;算法模板、数据结构 &#x1f516;少年有梦不应止于心动&#xff0c;更要付诸行动。 文章目录 &#x1f4cb;前言一. ⛳️使用数组模拟单链表讲解1.1 &#x1f514;为什么我们要使用数组去模拟单链表…

appium2.0.1安装完整教程+uiautomator2安装教程

第一步&#xff1a;根据官网命令安装appium&#xff08;Install Appium - Appium Documentation&#xff09; 注意npm前提是设置淘宝镜像&#xff1a; npm config set registry https://registry.npmmirror.com/ 会魔法的除外。。。 npm i --locationglobal appium或者 npm…

多线程 (上) - 学习笔记

前置知识 什么是线程和进程? 进程: 是程序的一次执行,一个在内存中运行的应用程序。每个进程都有自己独立的一块内存空间&#xff0c;一个进程可以有多个线程&#xff0c;比如在Windows系统中&#xff0c;一个运行的xx.exe就是一个进程。 线程: 进程中的一个执行流&#xff0…

Element-Ui定制Dropdown组件

1.效果 说明&#xff1a;移入后新增图标&#xff0c;然后移入后图标变色。当然大家可以想到用mouseover移入事件来实现移入颜色的变化&#xff0c;但是在使用Dropdown组件的时候&#xff0c;不支持这种写法。因此采用了原生的遍历对象的形式&#xff0c;为每一个item对象绑定鼠…

通过WinCC基本功能实现批次查询及批次报表

谈到WinCC中的批次数据处理和批次报表&#xff0c;也许有人会想到PM-Quality这款专业的批次报表软件。但如果你的银子有限&#xff0c;批次报表要求又比较简单&#xff0c;不妨看看此文。 —《通过 WinCC 基本功能实现批次数据过滤查询以及打印批次数据报表》 实现的功能描述 …

一维数组的定义

什么是数组&#xff1f; &#xff08;1&#xff09;数组是具有一定顺序关系的若干变量的集合&#xff0c;组成数组的各个变量统称为数组的元素 &#xff08;2&#xff09;数组中的各元素的数据类型要求相同&#xff0c;用数组名和下标确定&#xff0c;数组可以是一维的&#…

无经验小白开发一个 JavaWeb项目,需要注意哪些要点?

大家好我是咕噜铁蛋 &#xff0c;我收集了许多来自互联网的宝贵资源&#xff0c;这些资源帮助我学习和理解如何从零开始开发JavaWeb项目。今天&#xff0c;我将与大家分享一些关键的要点&#xff0c;包括项目规划、技术选型、数据库设计、代码编写和测试部署等。如果你有任何问…

大数据存储技术(3)—— HBase分布式数据库

目录 一、HBase简介 &#xff08;一&#xff09;概念 &#xff08;二&#xff09;特点 &#xff08;三&#xff09;HBase架构 二、HBase原理 &#xff08;一&#xff09;读流程 &#xff08;二&#xff09;写流程 &#xff08;三&#xff09;数据 flush 过程 &#xf…

Mysql数据库 19.Mysql 锁

MySQL锁 锁&#xff1a;锁是计算机用以协调多个进程间并发访问同一共享资源的一种机制&#xff0c;在数据库中&#xff0c;除传统的计算资源&#xff08;CPU、RAM、I/O&#xff09;的争用以外&#xff0c;数据也是一种供许多用户共享的资源&#xff0c;如何保证数据并发访问的一…

【MySQL备份】MySQL备份工具-MyDumper

目录 什么是MyDumper MyDumper优势有哪些 如何安装MyDumper 参数解释 1 mydumper参数解释 备份流程 一致性快照如何工作&#xff1f; 如何排除&#xff08;或包含&#xff09;数据库&#xff1f; 输出文件 Metadata文件 ​编辑 表数据 文件 表结构 文件 建库文件…

关于uview-ui的u-tabs标签滑块不居中的问题

在uniapp中&#xff0c;打开文件 uni_modules/uview-ui/components/u-tabs/u-tabs.vue 然后在style中添加以下代码即可 /deep/ .u-tabs__wrapper__nav__line {left: 18rpx; } 之前效果图&#xff1a; 之后效果图&#xff1a; 注意&#xff0c;代码中的18rpx需要自行调整

半导体:Gem/Secs基本协议库的开发(5)

此篇是1-4 《半导体》的会和处啦&#xff0c;我们有了协议库&#xff0c;也有了通讯库&#xff0c;这不得快乐的玩一把~ 一、先创建一个从站&#xff0c;也就是我们的Equipment端 QT - guiCONFIG c11 console CONFIG - app_bundle CONFIG no_debug_release # 不会生…

深入理解JVM设计的精髓与独特之处

这是Java代码的执行过程 从软件工程的视角去深入拆解&#xff0c;无疑极具吸引力&#xff1a;首个阶段仅依赖于源高级语言的细微之处&#xff0c;而第二阶段则仅仅专注于目标机器语言的特质。 不可否认&#xff0c;在这两个编译阶段之间的衔接&#xff08;具体指明中间处理步…

C语言----文件操作(二)

在上一篇文章中我们简单介绍了在C语言中文件是什么以及文件的打开和关闭操作&#xff0c;在实际工作中&#xff0c;我们不仅仅是要打开和关闭文件&#xff0c;二是需要对文件进行增删改写。本文将详细介绍如果对文件进行安全读写。 一&#xff0c;以字符形式读写文件&#xff…

一文搞懂OSI参考模型与TCP/IP

OSI参考模型与TCP/IP 1. OSI参考模型1.1 概念1.2 数据传输过程 2. TCP/IP2.1 概念2.2 数据传输过程 3. 对应关系4. 例子4.1 发送数据包4.2 传输数据包4.3 接收数据包 1. OSI参考模型 1.1 概念 OSI模型&#xff08;Open System Interconnection Reference Model&#xff09;&a…

MLX:苹果 专为统一内存架构(UMA) 设计的机器学习框架

“晨兴理荒秽&#xff0c;带月荷锄归” 夜深闻讯&#xff0c;有点兴奋&#xff5e; 苹果为 UMA 设计的深度学习框架真的来了 统一内存架构 得益于 CPU 与 GPU 内存的共享&#xff0c;同时与 MacOS 和 M 芯片 交相辉映&#xff0c;在效率上&#xff0c;实现对其他框架的降维打…

【后端卷前端3】

侦听器 监听的数据是 data()中的动态数据~响应式数据 <template><div><p>{{showHello}}</p><button click"updateHello">修改数据</button></div> </template><script>export default {name: "goodsTe…