C ++ Regular Expression (regex)

Source: Internet
Author: User
Tags visual studio 2010

Interest generated by the effect, even if the failure, but at least will not be extinct in the middle.

Regular Expressions. The syntax looks a lot better! This article provides a brief introduction: (Environment: Windows 7 + Visual Studio 2010)

# Include <regex> // header

1. Match the phone number

String tel_pattern ("13 ([5-8]) (\ d {8 })");

// Explanation: () indicates a subexpression, starting with a and 13. B, [5-8] indicates that the character is between '5' and '8'. c, \ escape, because d has a special meaning. d {8} represents eight numbers. Result: There are 11 numbers starting with 135-138.

String tel = "13512345678"; www.2cto.com

Bool match = regex_match (tel, tel_pattern );

2. Match the email address

String email_pattern ("(\ w +) (\. | _)? (\ W +) @ (\ w +) (\. (\ w +) + ");

// Explanation: w + indicates one or more words. | _ indicates. Or _,? 0 or 1, and + indicates repetition.

@ The meaning above is that there can be 1. Or _ between strings or no

@ Indicates that a word string starts with a. Word or multiple words.

3, separator string

[Cpp]
<Span style = "font-size: 14px;"> regex str_pattern ("(\\.)");
String str = "www.baidu.com ";
Sregex_token_iterator iter (str. begin (), str. end (), str_pattern,-1 );
Sregex_token_iterator end;
Vector <string> vec;
While (iter! = End)
{
Vec. push_back (* iter ++ );
Printf_s ("% s \ n", vec. back (). c_str ());
}
Printf_s ("% d \ n", vec. size (); </span>
Conclusion: Regular Expressions are powerful in usage and can be used to search, match, and separate expressions.

Important: the relationship between regular expressions and syntax tree and lexical analysis in compilation principles is too tight.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.