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++

php中世界最好的语言
Release: 2018-03-29 17:57:00
Original
1600 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template