search
HomeWeb Front-endJS TutorialDetailed introduction to the use of regular expressions in C++

This time I will bring you a detailed introduction to the use of regular expressions in C++. What are the precautions for using regular expressions in C++? The following is a practical case, let's take a look.

Regular expressionRegex (regular expression) is a powerful tool for describing character sequences. Regular expressions exist in many languages. C++11 has also included regular expressions as part of the new standard. Not only that, it also supports 6 different regular expression syntaxes, namely: ECMASCRIPT, basic, extended, awk, grep and egrep. ECMASCRIPT is the default syntax. We can specify which syntax to use when constructing the regular expression.

Regular expression is a text pattern. Regular expressions are powerful, convenient, and efficient text processing tools. Regular expressions themselves, coupled with general pattern notation like a pocket programming language, give users the ability to describe and analyze text. With additional support provided by specific tools, regular expressions can add, delete, separate, overlay, insert and trim various types of text and data.

A complete regular expression consists of two types of characters: special characters are called "meta characters", and others are "literal" or normal text characters text characters, such as letters, numbers, Chinese characters, and underscores). Regular expression metacharacters provide more powerful description capabilities.

Like text editors, most high-level programming languages ​​support regular expressions, such as Perl, Java, Python, and C/C++. These languages ​​have their own regular expression packages.

A regular expression is just a string, it has no length limit. "Subexpression" refers to a part of the entire regular expression, usually an expression within parentheses, or a multiple-choice branch separated by "|".

By default, letters in expressions are case-sensitive.

           

Commonly used metacharacters:

1.                                                   Commonly used metacharacters:

1.         “.”: Matches any single character except "\n", if you want to match, include "\n" For any characters including "[\s\S]", you need to use a pattern such as "[\s\S]";

2. "^": matches the input character

The beginning of the string, does not match Any character. To match the "^" character itself, you need to use "\^";

3. "$": Match the end of the input string. Do not match any characters. Match the "$" character itself. , need to use "\$";

4. "*": Match the previous character or subexpression zero or more times, "*" is equivalent to "{0,}", such as "\ ^*b" can match "b", "^b", "^^b",...;

5. "+": Match the previous character or subexpression one or more times, equivalent In "{1,}", such as "a+b" can match "ab", "aab", "aaab",...;

6. "?": Match the previous character zero or once Or subexpression, equivalent to "{0,1}", such as "a[cd]?" can match "a", "ac", "ad"; when this character follows any other qualifier "*" , "+", "?", "{n}", "{n,}", "{n,m}", the matching mode is "non-greedy". The "non-greedy" pattern matches the shortest possible string searched, while the default "greedy" pattern matches the longest possible string searched. For example, in the string "oooo", "o+?" only matches a single "o", while "o+" matches all "o";

7. "|": Logicalize the two matching conditions "Or" (Or) operation, such as the regular expression "(him|her)" matches "itbelongs to him" and "it belongs to her", but cannot match "itbelongs to them.";

8 "\": Mark the next character as a special character, text, back reference or octal escape character, for example, "n" matches the character "n", "\n" matches the newline character, and the sequence "\\" matches "\","\("match"(";###

9. “\w”: Match letters or numbers or underscores, any letter or number or underscore, that is, any one of A~Z, a~z,0~9,_;

10 . “\W”: Matches any character that is not letters, numbers, or underscores;

11. “\s”: Matches any whitespace characters, including spaces, tabs, form feeds, and other whitespace characters. Any one of them is equivalent to "[ \f\n\r\t\v]";

12. "\S": matches any character that is not a whitespace character, and is equivalent to "[^\f\ n\r\t\v]" is equivalent;

13. "\d": Matches numbers, any number, any one from 0 to 9, equivalent to "[0-9]" ;

14. "\D": Matches any non-digit character, equivalent to "[^0-9]";

15. "\b": Matches a word boundary , that is, the position between a word and a space, that is, the position between a word and a space, does not match any characters, for example, "er\b" matches "er" in "never", but does not match "" in "verb" er";

16. "\B": non-word boundary matching, "er\B" matches the "er" in "verb", but does not match the "er" in "never";

17. “\f”: Matches a newline character, equivalent to “\x0c” and “\cL”;

18. “\n”: Matches a newline character, equivalent to In "\x0a" and "\cJ";

19. "\r": matches a carriage return character, equivalent to "\x0d" and "\cM";

20 . "\t": Matches a tab character, equivalent to "\x09" and "\cI";

21. "\v": Matches a vertical tab character, equivalent to "\ x0b" and "\cK";

22. "\cx": matches the control character indicated by "x", for example, \cM matches Control-M or carriage return character, the value of "x" must be in Between "A-Z" or "a-z", if this is not the case, it is assumed that c is the "c" character itself;

23. "{n}": "n" is a non-negative integer, matching exactly n times, For example, "o{2}" does not match the "o" in "Bob", but matches the two "o"s in "food";

24. "{n,}":" n" is a non-negative integer, matching at least n times. For example, "o{2,}" does not match the "o" in "Bob", but matches all "o" and "o{1,}" in "foooood" Equivalent to "o+", "o{0,}" is equivalent to "o*";

25. "{n,m}": "n" and "m" are non-negative integers, where n

26. "x|y": Match "x" or "y", for example, "z|food" matches "z" or "food"; "(z|f)ood" matches "zood" or "food";

27. "[xyz]": character set, matches any character included, for example, "[abc]" matches "a" in "plain";

28. "[^xyz]": reverse Character set, matches any character not included, matches any character except "xyz", for example, "[^abc]" matches "p" in "plain";

29. "[a-z] ": Character range, matches any character within the specified range, for example, "[a-z]" matches any lowercase letter in the range from "a" to "z";

30. " [^a-z]": Reverse range character, matches any character that is not within the specified range. For example, "[^a-z]" matches any character that is not within the range of "a" to "z";

31. "( )": Define the expression between "(" and ")" as a "group" group, and save the characters matching this expression to a temporary area. A regular expression can save up to 9, they can be referenced with symbols from "\1" to "\9";

32. "(pattern)": Match pattern and capture the matching subexpression, you can use $0...$9 Property retrieves captured matches from the resulting "matches" collection;

 33.  “(?:pattern)”:匹配pattern但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配,这对于用”or”字符” (|)”组合模式部件的情况很有用, 如,”industr(?:y|ies)”是比”industry|industries”更简略的表达式;

 34.  “(?=pattern)”: 非获取匹配,正向肯定预查,在任何匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用。如,"Windows(?=95|98|NT|2000)"能匹配"Windows2000"中的"Windows",但不能匹配"Windows3.1"中的"Windows"。预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之后开始;

 35.  “(?!pattern)”: 非获取匹配,正向否定预查,在任何不匹配pattern的字符串开始处匹配查找字符串,该匹配不需要获取供以后使用。如"Windows(?!95|98|NT|2000)"能匹配"Windows3.1"中的"Windows",但不能匹配"Windows2000"中的"Windows";

 要匹配某些特殊字符,需在此特殊字符前面加上”\”,如要匹配字符”^”、”$”、”()”、”[]”、”{}”、”.”、”?”、”+”、”*”、”|”,需使用” \^”、” \$”、” \ (“、”\)”、” \ [“、”\]”、” \{“、”\}”、” \.”、” \?”、” \+”、” \*”、” \|”。

 在C++/C++11中,GCC版本是4.9.0及以上,VS版本为VS2013及以上时,会有regex头文件,此头文件中会有regex_match、regex_search、regex_replace等函数可供调用,以下是测试代码:

#include "regex.hpp" 
#include <regex> 
#include <string> 
#include <vector> 
#include <iostream> 
int test_regex_match() 
{ 
 std::string pattern{ "\\d{3}-\\d{8}|\\d{4}-\\d{7}" }; // fixed telephone 
 std::regex re(pattern); 
 std::vector<:string> str{ "010-12345678", "0319-9876543", "021-123456789"}; 
 /* std::regex_match: 
  判断一个正则表达式(参数re)是否匹配整个字符序列str,它主要用于验证文本 
  注意,这个正则表达式必须匹配被分析串的全部,否则返回false;如果整个序列被成功匹配,返回true 
 */ 
 for (auto tmp : str) { 
  bool ret = std::regex_match(tmp, re); 
  if (ret) fprintf(stderr, "%s, can match\n", tmp.c_str()); 
  else fprintf(stderr, "%s, can not match\n", tmp.c_str()); 
 } 
 return 0; 
} 
int test_regex_search() 
{ 
 std::string pattern{ "http|hppts://\\w*$" }; // url 
 std::regex re(pattern); 
 std::vector<:string> str{ "http://blog.csdn.net/fengbingchun", "https://github.com/fengbingchun", 
  "abcd://124.456", "abcd https://github.com/fengbingchun 123" }; 
 /* std::regex_search: 
  类似于regex_match,但它不要求整个字符序列完全匹配 
  可以用regex_search来查找输入中的一个子序列,该子序列匹配正则表达式re 
 */ 
 for (auto tmp : str) { 
  bool ret = std::regex_search(tmp, re); 
  if (ret) fprintf(stderr, "%s, can search\n", tmp.c_str()); 
  else fprintf(stderr, "%s, can not search\n", tmp.c_str()); 
 } 
 return 0; 
} 
int test_regex_search2() 
{ 
 std::string pattern{ "[a-zA-z]+://[^\\s]*" }; // url 
 std::regex re(pattern); 
 std::string str{ "my csdn blog addr is: http://blog.csdn.net/fengbingchun , my github addr is: https://github.com/fengbingchun " }; 
 std::smatch results; 
 while (std::regex_search(str, results, re)) { 
  for (auto x : results) 
   std::cout  str{ "123456789012345678", "abcd123456789012345678efgh", 
  "abcdefbg", "12345678901234567X" }; 
 std::string fmt{ "********" }; 
 /* std::regex_replace: 
  在整个字符序列中查找正则表达式re的所有匹配 
  这个算法每次成功匹配后,就根据参数fmt对匹配字符串进行替换 
 */ 
 for (auto tmp : str) { 
  std::string ret = std::regex_replace(tmp, re, fmt); 
  fprintf(stderr, "src: %s, dst: %s\n", tmp.c_str(), ret.c_str()); 
 } 
 return 0; 
} 
int test_regex_replace2() 
{ 
 // reference: http://www.cplusplus.com/reference/regex/regex_replace/ 
 std::string s("there is a subsequence in the string\n"); 
 std::regex e("\\b(sub)([^ ]*)"); // matches words beginning by "sub" 
 // using string/c-string (3) version: 
 std::cout <p>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!</p>
<p>推荐阅读:</p>
<p><a href="http://www.php.cn/js-tutorial-390700.html" target="_blank">使用正则表达式提取字符串详解(附代码)</a></p>
<p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-390698.html" target="_blank">容易产生错误的js手机号码验证</a><br></p></:string></:string></iostream></vector></string></regex>

The above is the detailed content of Detailed introduction to the use of regular expressions in C++. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools