Home Web Front-end JS Tutorial Detailed introduction to the use of regular expressions in C++

Detailed introduction to the use of regular expressions in C++

Mar 29, 2018 pm 05:57 PM
introduce use detailed

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<=m, matches at least n times and at most m times. For example, "o{1,3}" matches the first three o's in "foooooood", and 'o{0,1}' is equivalent to 'o?' , note that spaces cannot be inserted between commas and numbers; for example, "ba{1,3}" can match "ba" or "baa" or "baaa";

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  
#include  
#include  
#include  
int test_regex_match() 
{ 
 std::string pattern{ "\\d{3}-\\d{8}|\\d{4}-\\d{7}" }; // fixed telephone 
 std::regex re(pattern); 
 std::vector 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 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 << x << " "; 
  std::cout << std::endl; 
  str = results.suffix().str(); 
 } 
 return 0; 
} 
int test_regex_replace() 
{ 
 std::string pattern{ "\\d{18}|\\d{17}X" }; // id card 
 std::regex re(pattern); 
 std::vector 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 << std::regex_replace(s, e, "sub-$2"); 
 // using range/c-string (6) version: 
 std::string result; 
 std::regex_replace(std::back_inserter(result), s.begin(), s.end(), e, "$2"); 
 std::cout << result; 
 // with flags: 
 std::cout << std::regex_replace(s, e, "$1 and $2", std::regex_constants::format_no_copy); 
 std::cout << std::endl; 
 return 0; 
}

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

使用正则表达式提取字符串详解(附代码)

容易产生错误的js手机号码验证

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Detailed introduction to what wapi is Detailed introduction to what wapi is Jan 07, 2024 pm 09:14 PM

Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Detailed explanation of whether win11 can run PUBG game Detailed explanation of whether win11 can run PUBG game Jan 06, 2024 pm 07:17 PM

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Introduction to Python functions: Introduction and examples of exec function Introduction to Python functions: Introduction and examples of exec function Nov 03, 2023 pm 02:09 PM

Introduction to Python functions: Introduction and examples of exec function Introduction: In Python, exec is a built-in function that is used to execute Python code stored in a string or file. The exec function provides a way to dynamically execute code, allowing the program to generate, modify, and execute code as needed during runtime. This article will introduce how to use the exec function and give some practical code examples. How to use the exec function: The basic syntax of the exec function is as follows: exec

Which computer should Geographic Information Science majors choose? Which computer should Geographic Information Science majors choose? Jan 13, 2024 am 08:00 AM

Recommended computers suitable for students majoring in geographic information science 1. Recommendation 2. Students majoring in geographic information science need to process large amounts of geographic data and conduct complex geographic information analysis, so they need a computer with strong performance. A computer with high configuration can provide faster processing speed and larger storage space, and can better meet professional needs. 3. It is recommended to choose a computer equipped with a high-performance processor and large-capacity memory, which can improve the efficiency of data processing and analysis. In addition, choosing a computer with larger storage space and a high-resolution display can better display geographic data and results. In addition, considering that students majoring in geographic information science may need to develop and program geographic information system (GIS) software, choose a computer with better graphics processing support.

Detailed introduction to whether i5 processor can install win11 Detailed introduction to whether i5 processor can install win11 Dec 27, 2023 pm 05:03 PM

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

Introducing the latest Win 11 sound tuning method Introducing the latest Win 11 sound tuning method Jan 08, 2024 pm 06:41 PM

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

Introduction to edge shortcut keys Introduction to edge shortcut keys Jul 12, 2023 pm 05:57 PM

In today's fast life, in order to improve work efficiency, shortcut keys are an essential work requirement. A shortcut key is a key or key combination that provides an alternative way to perform an action normally performed using a mouse. So what are the edge shortcut keys? What are the functions of edge shortcut keys? The editor below has compiled an introduction to edge shortcut keys. Friends who are interested should come and take a look! Ctrl+D: Add the current page to favorites or reading list Ctrl+E: Perform a search query in the address bar Ctrl+F: Find on the page Ctrl+H: Open the history panel Ctrl+G: Open the reading list panel Ctrl +I: Open the favorites list panel (the test does not seem to work) Ctrl+J: Open

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

See all articles