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

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>",   // datareg1);                // regular expressionout(found);// find XML/HTML-tagged value (tags before and after the value must match):regex reg2("<(.*)>.*</\\1>");found = regex_match ("<tag>value</tag>",        // datareg2);                     // regular expressionout(found);// find XML/HTML-tagged value (using grep syntax):regex reg3("<\\(.*\\)>.*</\\1>",regex_constants::grep);found = regex_match ("<tag>value</tag>",        // datareg3);                     // regular expressionout(found);// use C-string as regular expression (needs explicit cast to regex):found = regex_match ("<tag>value</tag>",        // dataregex("<(.*)>.*</\\1>"));  // regular expressionout(found);cout << endl;// regex_match() versus regex_search():found = regex_match ("XML tag: <tag>value</tag>", regex("<(.*)>.*</\\1>"));         // fails to matchout(found);found = regex_match ("XML tag: <tag>value</tag>", regex(".*<(.*)>.*</\\1>.*"));     // matchesout(found);found = regex_search ("XML tag: <tag>value</tag>", regex("<(.*)>.*</\\1>"));        // matchesout(found);found = regex_search ("XML tag: <tag>value</tag>", regex(".*<(.*)>.*</\\1>.*"));    // matchesout(found);
}
输出:
found
found
found
foundnot 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 matchbool 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):    30matches:<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:   firstvalue: Nico
match:  <last>Josuttis</last>tag:   lastvalue: Josuttis
match:  <first>Nico</first>tag:   firstvalue: Nico
match:  <last>Josuttis</last>tag:   lastvalue: 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(), // sequencereg,                       // token separator{0,2});      // 0: full match, 2: second substringsregex_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 spacessregex_token_iterator p(names.cbegin(),names.cend(),  // sequencesep,                          // separator-1);        // -1: values between separatorssregex_token_iterator e;for ( ; p!=e ; ++p ) {cout << "name:  " << *p << endl;}
}
输出:
match:  <first>Nico</first>
match:  Nico
match:  <last>Josuttis</last>
match:  Josuttisname:  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;     //replacementcout << 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 entriesstring pat1 = R"(\\.*index\{([^}]*)\})";       // first capture groupstring pat2 = R"(\\.*index\{(.*)\}\{(.*)\})";  // 2nd and 3rd capture groupregex 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.mzph.cn/news/226754.shtml

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

相关文章

ProroBuf C++笔记

一.什么是protobuf Protocol Buffers是Google的⼀种语⾔⽆关、平台⽆关、可扩展的序列化结构数据的⽅法&#xff0c;它可⽤于&#xff08;数据&#xff09;通信协议、数据存储等。Protocol Buffers 类⽐于XML&#xff0c;是⼀种灵活&#xff0c;⾼效&#xff0c;⾃动化机制的结…

SpringData自定义操作

一、JPQL和SQL 查询 package com.kuang.repositories;import com.kuang.pojo.Customer; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.PagingAndSortingR…

Java研学-HTML

HTML 1 介绍 HTML(Hypertext Markup Language) 超文本标记语言。静态网页&#xff0c;用于在浏览器上显示数据 超文本: 指页面内可以包含图片、链接&#xff0c;甚至音乐、程序等非文字元素。 标记语言: 使用 < > 括起来的语言 超文本标记语言的结构, 包括“头”部分&am…

javaEE -17(13000字 CSS3 入门级教程)

一&#xff1a;CSS3 简介 CSS3 是 CSS2 的升级版本&#xff0c;它在 CSS2 的基础上&#xff0c;新增了很多强大的新功能&#xff0c;从而解决一些实际面临的问题&#xff0c;CSS3 在未来会按照模块化的方式去发展&#xff1a;https://www.w3.org/Style/CSS/current-work.html …

Guardrails for Amazon Bedrock 基于具体使用案例与负责任 AI 政策实现定制式安全保障(预览版)

作为负责任的人工智能&#xff08;AI&#xff09;战略的一部分&#xff0c;您现在可以使用 Guardrails for Amazon Bedrock&#xff08;预览版&#xff09;&#xff0c;实施专为您的用例和负责任的人工智能政策而定制的保障措施&#xff0c;以此促进用户与生成式人工智能应用程…

电子/计算机专业词汇中法对照(持续更新)

文章目录 【计算机词汇】计算机基础符号数据结构与算法网络编程 | ProgrammationGit 【电气词汇】电气基础数电&模电电气 【数学词汇】基础数学电气类数学缩写控制理论 | Systme linaire/asservi | Asservissement 【管理词汇】财政|市场 |Finance|Marketing 【计算机词汇】…

TCP/UDP 的特点、区别及优缺点

1.TCP协议 传输控制协议&#xff08;TCP&#xff0c;Transmission Control Protocol&#xff09;是一种面向连接的、可靠的、基于字节流的传输层通信协议。TCP协议通过建立连接、数据确认&#xff08;编段号和确认号&#xff09;和数据重传等机制&#xff0c;保证了数据的可靠性…

智能优化算法应用:基于哈里斯鹰算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于哈里斯鹰算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于哈里斯鹰算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.哈里斯鹰算法4.实验参数设定5.算法结果6.…

【ArkTS】循环控制与List的使用

ArkTS如何进行循环渲染 现有数据如下 class Item{name:stringimage:Resourceprice:numberdicount:numberconstructor(name:string,image:Resource,price:number,dicount?:number) {this.name namethis.image imagethis.price pricethis.dicount dicount} }private items…

力扣72. 编辑距离

动态规划 思路&#xff1a; 假设 dp[i][j] 是 word1 前 i 个字母到 word2 前 j 个字母的编辑距离&#xff1b;那么状态 dp[i][j] 状态的上一个状态有&#xff1a; dp[i - 1][j]&#xff0c;word1 前 i - 1 个字母到 word2 前 j 个字母的编辑距离&#xff0c;此状态再插入一个字…

linux性能优化-上下文切换

如何理解上下文切换 Linux 是一个多任务操作系统&#xff0c;它支持远大于 CPU 数量的任务同时运行&#xff0c;这是通过频繁的上下文切换、将CPU轮流分配给不同任务从而实现的。 CPU 上下文切换&#xff0c;就是先把前一个任务的 CPU 上下文&#xff08;CPU 寄存器和程序计数…

JVM学习之JVM概述

JVM的整体结构 Hotspot VM是目前市面上高性能虚拟机代表作之一 它采用解释器与即时编译器并存的架构 在今天&#xff0c;Java程序的运行性能已经达到了可以和C/C程序一较高下的地步 Java代码执行流程 具体图为 JVM架构模型 Java编译器输入的指令流基本上是一种基于 栈的指令…

Transformer的学习

文章目录 Transformer1.了解Seq2Seq任务2.Transformer 整体架构3.Encoder的运作方式4.Decoder的运作方式5.AT 与 NAT6.Encoder 和 Decoder 之间的互动7.Training Transformer 1.了解Seq2Seq任务 NLP 的问题&#xff0c;都可以看做是 QA&#xff08;Question Answering&#x…

只要陪着你——来自歌手朱卫明的音乐与情感的交织

在这个五彩斑斓又纷繁复杂的世界中&#xff0c;情感是我们最珍贵的财富。有一种情感&#xff0c;它不受时间的限制&#xff0c;不受空间的束缚&#xff0c;它能够跨越四季&#xff0c;穿越风雨&#xff0c;那就是陪伴。朱卫明的歌声就是这种陪伴的象征&#xff0c;他用音乐为我…

vue自定义指令及常用的自定义指令封装

vue2 自定义指令 官网链接https://v2.cn.vuejs.org/v2/guide/custom-directive.html 指令注册 这里是一个 Vue2 的指令合集&#xff0c;详细的指令移步下面具体的指令文章&#xff0c;现在我们在这里要介绍如何在项目中统一管理和使用这些指令。 注册指令 单文件引入注册 …

机器学习的12个基础问题

1.阐述批归一化的意义 算法 1&#xff1a;批归一化变换&#xff0c;在一个 mini-batch 上应用于激活 x。 批归一化是一种用于训练神经网络模型的有效方法。这种方法的目标是对特征进行归一化处理&#xff08;使每层网络的输出都经过激活&#xff09;&#xff0c;得到标准差为 …

K8S的安装工具

kubectl Kubernetes 命令行工具 kubectl&#xff0c; 让你可以对 Kubernetes 集群运行命令。 你可以使用 kubectl 来部署应用、监测和管理集群资源以及查看日志。 有关更多信息&#xff0c;包括 kubectl 操作的完整列表&#xff0c;请参见 kubectl参考文件。 kubectl 可安装在…

vue路由传参(query和params两种方式)

vue传参常用的两种传参方式 query方式&#xff1a; 参数拼接在url上刷新页面不会丢失数据但如果传递对象或者数组过大时&#xff0c;会出现url过长导致异常错误的问题参数为对象或者对象组成的数组时&#xff0c;需要使用JSON.stringify()格式化&#xff0c;接收时JSON.parse(…

2. 皇后的控制力

题目描述&#xff1a; 我们对八皇后问题进行扩展。 国际象棋中的皇后非常神勇&#xff0c;一个皇后可以控制横、竖、斜线等4个方向&#xff08;或者说是8个方向&#xff09;&#xff0c;只要有棋子落入她的势力范围&#xff0c;则必死无疑&#xff0c;所以对方的每个棋子都要…

1.4【应用开发】缓冲区(一)

写在前面 缓冲区是存储像素数据的内存区域。多个缓冲区可以与窗口或流相关联,但只有一个缓冲区可以与位图相关联。 一,创建缓冲区 你可以创建内部缓冲区和外部缓冲区,如下: 1.1 内部缓冲区 我们可以通过调用以下Screen API函数来为位图,流,窗口创建内部缓冲区: sc…