Regex - C++11, 6 of n

C++标准库第17章:tuple、bitset、regex与random的工程价值 在C++开发中,结构化数据表达、位级语义建模、声明式文本处理和可重现随机性是高频基础需求。std::tuple提供编译期类型安全的异构数据组合能力,替代冗余struct定义与脆弱pair嵌套;std::bitset将位操作升格为具备语义、可测试、支持运算符重载的数学对象,广泛用于协议解析与硬件寄存器建模;std::regex实现从过程式字符串扫描到声明式模式匹配的范式跃迁,显著提升HTTP头、日志、配置解析等场景的可维护性;std::random通过引擎-分布分离设计,解决rand()的全局状态、质量缺陷与 阅读详情
1) Raw string
R"delim(...)delim", where delim is a character sequence of at most 16 basic characters except the backslash, whitespace and parentheses.
2) Note regex algorithm is greedy
3) Main interfaces

    a. basic_regex<> template: holds the regular expression pattern
(predefined regex, wregex)
    b. match_results<> template: carry back the match results (predefined s/c/ws/wcmatch, s for string, c for const char*)
    c. regex_match(): checks whether the whole character sequence matches a regular expression

    d. regex_search(): checks whether the character sequence partially matches a regular expression
     f. regex_replace(): replace character sequences that match a regular expression.

4) Basic matching examples
regex reg1("<.*>.*</.*>");
bool found = regex_match ("<tag>value</tag>", reg1);

regex reg2("<(.*)>.*</\\1>");  // grouping and forward referencing
found = regex_match ("<tag>value</tag>", reg2);

// use grep grammer
regex reg3("<\\(.*\\)>.*</\\1>",regex_constants::grep);
found = regex_match ("<tag>value</tag>", reg3);

found = regex_match ("XML tag: <tag>value</tag>", regex(R"#<(.*)>.*</\1>#")); // fails to match
found = regex_search ("XML tag: <tag>value</tag>", regex(R"#<(.*)>.*</\1>#")); // match

5) match_results carry back the detail match result

match_results object m has a state which provides the following interface:
In general, the match_results object contains:
– A sub_match object m[0] for all the matched characters
– A prefix(), a sub_match object that represents all characters before the first matched character
– A suffix(), a sub_match object that represents all characters after the last matched character
• In addition, for any capture group, you have access to a corresponding sub_match object m[n].
• size() yields the number of sub_match objects (including m[0]).
• All sub_match objects are derived from pair<> and have the position of the first character as
member first and the position after the last character as member second. In addition, str()
yields the characters as a string, length() yields the number of characters, operator << writes
the characters to a stream, and an implicit type conversion to a string is defined.

In addition, the match_results object as a whole provides:
– member function str() to yield the matched string as a whole (calling str() or str(0))
or the nth matched substring (calling str(n)), which is empty if no matched substring exists
(thus, passing an n greater than size() is valid)
– member function length() to yield the length of the matched string as a whole (calling
length() or length(0)) or the length of the nth matched substring (calling length(n)),
which is 0 if no matched substring exists (thus, passing an n greater than size() is valid)
– member function position() to yield the position of the matched string as a whole (calling
position() or position(0)) or the position of the nth matched substring (calling
length(n))
– member functions begin(), cbegin(), end(), and cend() to iterate over the sub_match
objects m[0] to m[n]

6) regex_iterator<>, predefinesare s/c/w/wc regex_iterator
Examples:
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;
                           });

7) regex_token_iterator<> tokenizer, predefines are s/c/w/wc regex_token_iterator
Example:
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 != end ; ++p ) {
    cout << "name: " << *p << endl;
}

8) regex_replace
string data = "<person>\n"
                   "<first>Nico</first>\n"
                   "<last>Josuttis</last>\n"
                   "</person>\n";
regex reg("<(.*)>(.*)</(\\1)>");
// print data with replacement for matched patterns
cout << regex_replace (data, // data
                                  reg, // regular expression
                                  "<$1 value=\"$2\"/>") // replacement
       << endl;
// same using sed syntax
cout << regex_replace (data, // data
                                  reg, // regular expression
                                  "<\\1 value=\"\\2\"/>", // replacement
                                  regex_constants::format_sed) // format flag
      << endl;
// use iterator interface, and
// - format_no_copy: don’t copy characters that don’t match
// - format_first_only: replace only the first match found
string res2;
regex_replace (back_inserter(res2), // destination
                      data.begin(), data.end(), // source range
                      reg, // regular expression
                      "<$1 value=\"$2\"/>", // replacement
                      regex_constants::format_no_copy | regex_constants::format_first_only);// format flags
cout << res2 << endl;

                                            Regex Replacement Symbols

9) Regex flags

Examples:
// case-insensitive find LaTeX index entries
string pat1 = R"(\\.*index\{([^}]*)\})"; // first capture group
string pat2 = R"(\\.*index\{(.*)\}\{(.*)\})"; // 2nd and 3rd capture group
// grep and egrep can search for multiple regular expressions separated by '\n' at the same time
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;
}


Input samples:
\chapter{The Standard Template Library}
\index{STL}%
\MAININDEX{standard template library}%
\SEEINDEX{standard template library}{STL}%
This is the basic chapter about the STL.
\section{STL Components}
\hauptindex{STL, introduction}%
The \stl{} is based on the cooperation of

...

10) The regex ECMAScript grammar and special chars

                                                                ECMAScript grammar

                                                  Character classes in ECMAScript
(11)  Grammar differences

(12) Regex exception
exception code to explanation string for debugging
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";
}

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;
    }
}

C++通用工具库cpp-utilities:告别重复造轮子,提升开发效率 在C++开发中,字符串处理、文件操作、时间日期等基础功能是每个项目都绕不开的通用需求。这些看似简单的功能,若每次都从零实现或从网络拼凑,不仅效率低下,还会引入风格不一、质量参差不齐的代码,为项目埋下隐患。cpp-utilities正是为解决这一痛点而生的轻量级头文件库,它遵循现代C++标准,提供了一套经过充分测试、高效可靠的通用工具集。其核心价值在于通过模块化设计,将开发者从重复劳动中解放出来,让开发者能更专注于核心业务逻辑。无论是快速原型验证,还是需要长期维护的生产项目,cpp-utilities都能作为 阅读详情

相关推荐

C++正则表达式性能优化:从std::regex瓶颈到高效解决方案

正则表达式是文本处理的强大工具,通过模式匹配实现复杂字符串搜索与替换。其核心原理基于有限状态机,通过回溯算法尝试不同匹配路径,但这也可能引发性能问题,尤其是灾难性回溯。在C++开发中,标准库std::regex常因默认ECMAScript引擎、频繁回溯及构造开销成为性能瓶颈。优化正则表达式性能对提升数据处理效率、保障系统响应至关重要,尤其在高频日志解析、数据清洗等场景。通过避免嵌套量词、预编译正则对象、选用RE2或PCRE等高效库,可显著提升匹配速度。本文聚焦C++正则表达式性能优化,针对std::rege

weixin_34033624的博客 368

C++ 11 正则表达式

阅读一下C++ 11正则的文档

Abel's Blog 4218

DASH 流媒体协议(Dynamic Adaptive Streaming over HTTP)概述——起源、MPD文件解析、相关项目

简单介绍DASH的起源与发展、MPD文件简要解析、相关项目,以及常见流媒体协议的比较

farewellyi的博客 6880

Python 学习所遇问题

1、今天第一天学习,遇到了第一个错误 错误代码: print ‘hello’ 错误提示:missing parentheses in call to print (parentheses 圆括号的意思 , 在print的调用方法上丢失了圆括号) 错误解答:python3 取消了这样的用法,改用print (‘hello’)这样的用法 ...

Light_Jewel的专栏 608

基于Web的智能家居(源码+开题)

实践上,智能家居系统的普及和应用将极大改善人们的居住体验,提高生活质量,同时也有助于促进智能家居产业链的发展和完善,为社会经济发展注入新的活力。此外,本研究还将对基于Web的智能家居系统的用户体验进行深入研究,通过用户调研和数据分析,不断优化系统功能和界面设计,提升用户的使用体验和满意度。针对以上问题,本研究将综合运用物联网、云计算、大数据等新一代信息技术,通过系统架构设计、功能模块开发、安全性保障、用户体验优化等多个方面的研究工作,力求为基于Web的智能家居系统的研发和应用提供全面而有效的解决方案。

sryue06的博客 1902

从零构建:如何用MATLAB和SDR硬件搭建你的第一个OFDM卫星通信原型系统

本文详细介绍了如何利用MATLAB和SDR硬件从零构建OFDM卫星通信原型系统。通过核心组件选型、开发环境配置、OFDM算法实现到系统集成与优化的完整流程,帮助通信工程学生和DIY爱好者快速掌握软件无线电技术在卫星通信中的应用。特别推荐使用HackRF One和MATLAB工具箱实现高性价比的OFDM系统验证。

pz890123456的博客 378

最全的正则(python)基础知识

正则表达式 简介 起源于1951年数学家斯蒂芬·科尔·克莱尼发明的一种称之为“正则集合”的数学符号。 定义 即文本的高级匹配模式,提供搜索,替换等功能。其本质是由一系列字符和特殊符号构成的字串,这个字串即正则表达式。 原理 通过普通字符和有特定含义的字符,来组成字符串,用以描述一定的字符串规则,比如:重复,位置等,来表达某类特定的字符串,进而匹配。 普通字符 匹配规则:每个普通字符匹配其对应的字符 e.g. In : re.findall('ab',"abcdefabcd") Out: ['ab

Bruce.D的博客 1146

处理图数据, 安装“Pytorch“ + 图神经网络开源框架“PyG “+ “ogb“使用

"OGB" OSError: [WinError 127] 找不到指定的程序。1.[遇到这类问题往往跟torch安装的工具包(如torch-sparse,torch-scatter,torch-cluster)版本没对应上有关](https://blog.youkuaiyun.com/weixin_42358688/article/details/117433691)2.[OGB使用环境安装与依赖](https://ogb.stanford.edu/docs/home/)Data Loaders3.[torch-geo

Fuguir™的博客 3698

regex

The regex match and search interface //main.cpp #include #include using namespace std; void out(bool b) { cout << (b ? "found" : "not found") << endl; } int main() { // find XML/HTML-tagged

十年磨一剑 884

基于STM32+OV7670的图像采集系统(基础篇:ov7670介绍)

一、简单认识 先来看一下外观: OV7670,图像传感器,体积小,工作电压低,提供单片VGA摄像头和影像处理器的所有功能。通过SCCB总线控制,可以输入整帧、子采样、取窗口等方式的各种分辨率8位影像数据。 其他介绍比较繁琐,这里就不一一赘述了,我们只需要知道它是通过SCCB总线控制的就行了。 带FIFO与不带FIFO 目前市场上购买的ov7670模块分为两种,一种是不带FIFO芯片、一种是带FIFO芯片的。 FIFO是什么:(First Input First Output)先入先出的意思,

m0_59113542的博客 4万+

麒麟v10系统安装

麒麟v10系统安装

喜文BLOG 1万+

mysql的正则表达式

跟着官网学习 https://dev.mysql.com/doc/refman/8.0/en/regexp.html Regular Expressions Table 12.13 Regular Expression Functions and Operators Name Description NOT REGEXP Negation of REGEXP REGEXP Whether string matches regular expression REGEXP_INSTR() Startin

eeprom的博客 1360

AD9914数字斜坡模式使用

类似的,如果DRG输出处于负斜率斜坡中间,DRCTL引脚由逻辑0变为逻辑1,那么DRG会立即切换成正斜率参数,恢复在两个限值之间振荡输出。当两个非驻留位同时设置时,每次DRG输出达到编程设定的上限值或下限值后(假定DRG过输出使能位(0x01[13])已设置),DROVER信号会产生一个正脉冲(两个DDS时钟周期)。不过,在非驻留操作中,DRG输出不一定保持在上下限值。例如,设置数字斜坡非驻留高位,则当达到上限值时,DRG会自动(立即)跳到下限值(这一过程并非以斜坡方式返回下限值,而是直接跳至下限值)。

wangjie36的博客 3864

c++ regex 正则表达式使用

文章目录概述正则表达式库例子 概述 正则表达式是在c++11之后才被支持,叫正则表达式库。 使用的时候要包含&lt;regex&gt;头文件 正则表达式库 正则表达式有3个主要的算法 regex_match regex_search regex_replace 既然出现在c++11版本,那么迭代器这一重要的特性肯定也是要有的 regex_iterator regex_token_it...

一只懒虫的博客 4814

OpenClaw Docker 安装与部署教程,环境隔离不冲突技术指南

本文介绍了使用Docker容器化部署OpenClaw的完整教程。首先通过流程图详细说明了Docker环境检测流程,包括系统支持性检查、Docker安装状态验证、版本检测和服务配置等步骤。然后提供了Windows、macOS和Linux(Ubuntu/CentOS)系统下的Docker安装指南,涵盖从下载、安装到权限配置的全过程。最后介绍了OpenClaw官方镜像的拉取方法以及自定义镜像构建的Dockerfile示例。该教程适用于开发和生产环境,利用Docker实现环境隔离和快速部署。

一键难忘的博客 987

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

c++11特性之正则表达式

C++11中也将正则表达式纳入了新标准的一部分,不仅如此,它还支持了6种不同的正则表达式的语法,分别是:ECMASCRIPT、basic、extended、awk、grep和egrep。其中ECMASCRIPT是默认的语法,具体使用哪种语法我们可以在构造正则表达式的时候指定。正则表达式库提供表示正则表达式,这是一种用于字符串内执行模式匹配小型的语言的类。主要的类: basic_regex reg

一蓑烟雨任平生 也无风雨也无晴 5157

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

边用llama.cpp边学C++:Windows 11下真实工程驱动的入门路径

C++是一门强工程导向的语言,其核心价值在于对内存、硬件和系统资源的直接掌控。理解std::vector的RAII语义、std::thread的生命周期管理、CUDA与CPU协同的构建逻辑,远比孤立记忆语法更重要。llama.cpp作为轻量级但工业级的大模型推理引擎,天然融合了现代C++关键特性(如constexpr、模板元编程、跨平台条件编译)与底层实践(mmap内存映射、AVX指令对齐、OpenMP并发优化),成为连接语法知识与真实系统行为的理想桥梁。尤其在Windows 11 + CUDA环境下,从编

weixin_33700350的博客 407

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

活用regex的例子

在reddit推荐的文章上看到的。下面的代码在CMD窗口下运行通过。如果在BASH下面运行,单引号和双引号要对调。perl -wle "print prime if (1 x shift) !~ /^1?$|^(11+?)/1+$/" 任意一个数>Python的代码是:import redef is_prime(num):    return not re.match(

负暄琐话 4935

terminate called after throwing an instance of 'std::regex_error'(C++11)

#PS:要转载请注明出处,本人版权所有#PS:这个只是 《 我自己 》理解,如果和你的 #原则相冲突,请谅解,勿喷最近修改一个程序,增加了一些功能,为了方便移植,要用到C++11的正则表达式。这里我就想说明的是:TMD,GCC 语法实现了,库没有写完。。。QAQ,WC。什么不说了。目标:得到url(类似http://1.1.1.1:9001/group1/M00/00/37/wKgf

Sky的专栏 1万+

Boost.Regex:C++正则表达式高效处理指南

正则表达式作为文本处理的瑞士军刀,通过特定语法规则实现高效模式匹配与数据提取。其核心原理是基于有限状态自动机的字符串匹配算法,在数据验证、日志分析和文本清洗等场景具有不可替代的价值。Boost.Regex作为C++生态中成熟的解决方案,不仅提供Perl风格语法支持,还通过预编译优化和Unicode处理能力显著提升工程实践效率。针对性能敏感场景,合理使用捕获组控制和原子分组等技术可避免回溯爆炸问题。该库与CMake/vcpkg等现代构建工具的无缝集成,使其成为跨平台C++项目中处理复杂文本的首选方案。

weixin_30855099的博客 374

C++标准库第17章:tuple、bitset、regex与chrono工程实践指南

C++标准库中的tuple、bitset、regex和chrono等设施,是类型安全、位操作、文本解析与时间控制的基础抽象。其设计遵循零成本抽象原则,通过编译期计算、EBO优化与单调时钟保障,在嵌入式、高频交易和工业控制系统中实现毫秒级精度、位级内存压缩与线性匹配性能。这些组件并非语法糖,而是填补C++类型系统结构性缺口的关键工具:tuple支持异构数据原子封装,bitset提供可验证的位级操作语义,regex兼顾安全与裁剪能力,chrono明确区分steady_clock与system_clock适用边界

weixin_30666401的博客 340

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

文章目录简介主类算法迭代器异常示例&输出 简介 定义于头文件<regex> 正则表达式库提供表示正则表达的类,正则表达式是一种用于在字符串中匹配模式的微型语言。下列数种对象上的操作能刻画几乎所有带正则表达式的操作: 目标序列。为模式而搜索到的字符序列。这可以是二个迭代器所指定的范围、空终止字符串或一个 std::string 。 模式。这是正则表达式自身。它确定构成匹配者。它...

cout0 429

C++标准库特殊设施:bitset、regex与random工程实践指南

C++标准库中的特殊设施(如std::bitset、std::regex、std::random_device)并非边缘功能,而是支撑高可靠性、高性能与类型安全系统的核心组件。其设计本质是将编译期约束、运行时抽象与工业级验证相结合:bitset通过模板参数实现位运算零开销优化;regex封装模式匹配的语义抽象,但需预编译规避引擎差异风险;random设施终结rand()的线程不安全与分布偏差问题,依托引擎+分布分离架构保障统计严谨性。这些设施广泛应用于网络协议解析、日志处理、配置管理、压测模拟等关键场景,是

weixin_30653023的博客 444

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

无聊写简单题的时候顺便学了一下这个强大的工具。 常用函数: regex_match:全文匹配,要求整个字符串符合正则表达式的匹配规则。用来判断一个字符串和一个正则表达式是否模式匹配,如果匹配成功则返回true,否则返回false。 regex_search:搜索匹配,根据正则表达式来搜索字符串中是否存在符合规则的子字符串。 regex_replace:替换匹配,即可以将符合匹配规则的子字符串替换为其他字符串。要求输入一个正则表达式,以及一个用于替换匹配子字符串的格式化字符串。这个格式化字符串可以通过转义序列

wulalalawu的博客 429

C++ 11 regex正则表达式匹配所有内容,包括空格回车换行>(.|\\r|\\n)*?

const std::regex pattern( "(.|\\r|\\n)*?"); if( std::regex_search(" dfg\rsdf\ngsdfg ", result, pattern ) ) { MessageBox(nullptr,result.str().c_str(),"",MB_OK); }

brook0344的专栏 6525
上一篇: string - C++11, 5 of n
下一篇: IO Stream
CPP_CHEN
博客等级 码龄20年 15粉丝 132原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值