正则表达式(Regular Expression)是一种描述字符序列的方法,是处理字符序列的一种强大的计算工具!(字符串的匹配、查找、替换)
1.ECMAScript :ECMA-262规范:
ECMAScript是一种由Ecma国际(前身为欧洲计算机制造商协会,英文名称是European Computer Manufacturers Association)通过ECMA-262标准化的脚本程序设计语言。这种语言在万维网上应用广泛,它往往被称为JavaScript或JScript,所以它可以理解为是javascript的一个标准,但实际上后两者是ECMA-262标准的实现和扩展。
参考
[1]https://baike.baidu.com/item/ECMAScript/1889420?fr=aladdin
[2]官网:http://www.ecma-international.org/publications/standards/Ecma-262.htm
[3]W3School:ECMAScript 语法:http://www.w3school.com.cn/js/pro_js_syntax.asp
参考资料:
[1][2]斯坦利·李普曼, 约瑟·拉乔伊, 芭芭拉·默,等. C++ Primer中文版(第5版)[J]. 中国科技信息, 2013(20):17章:标准库特殊设施
ECMAScript正则表达式的一点特性:
- \{d} 表示单个数组,而\{d}{n} 表示一个由n个数字组成的序列。(如:\{d}{3} 用来匹配3个数字组成的序列)d:digit 数字
- 在方括号[]中的字符集表示匹配这些字符中的任意一个。(如:[-. ]匹配一个短线- 或点. 或 空格符,注:在[]没有特殊含义的字符。)
- 后接'?'的组件是可选的(及可有可无的),(如:\{d}{3}[-. ]?\{d}{4} 匹配这样的序列:开始是3个数字,然后是一个可选的短线-或点.或 空格符,然后是4个数字,次模式可以匹配 555-0123或555.0123或555 0123或5550123)
- 与C/C++常量字符串中的转移字符一样,ECMAScript使用\表示一个字符本身而不是其特殊含义。括号()在ECMAScript中是特殊字符,我们的模式包括括号(),因此,必须用\(和\)来表示一对括号()。
- 反斜线\是C++的特殊字符,因此在C++代码中写ECMAScript的模式pattern时,必须用一个额外的反斜线\来告诉C++我们需要一个反斜线字符而不是一个特殊字符。因此,用\\{d}{3}来表示正在表达式\{d}{3}
子表达式的概念:
正则表达式中的模式通常包含一个或多个子表达式(subexpression)。一个子表达式是模式的一部分,本身也具有子模式串的意义。通常用括号()来表示子表达式。
子表达式的应用:
- 子表达式用于数据验证
- 使用子匹配操作
子表达式用于数据验证:验证必须匹配特点格式的字符串数据。
例子:美国的电话号码由10位数字,包含开头的3位为区号,和后面的7位为本地号码。
区号通常放在()里,但这不是必须的,剩余的数字可以用一个短线- 或点. 或空格 分割,但这也不是必须的。
我们希望接收任何这种格式数据而拒接其他格式的数据。
首先,用一个正则表达式来找到可能是电话号码的序列,
然后再调用一个函数来验证其有效性(就是检查输入的格式对不对!)。
那么,这种电话号码的格式为:(d表示一个数字,分隔符可以是[- . ]空格中的任一个)
(ddd)分隔符ddd分隔符dddd
再C++代码中,该正则表达式为:
string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
解读时:使用的子表达式(),并且要去除反斜线\
- (\\()? 表示区号部分各选的左括号
- (\\d{3}) 表示3个数字组成的区号
- (\\))? 表示区号部分可选的右括号(注意:一旦有了左括号就必须要有右括号)
- ([-. ])? 表示区号后可选的分隔符
- (\\d{3}) 表示号码的下面三位数组
- ([-. ])? 表示数字部分可选的分隔符
- (\\d{4}) 表示号码的最后4位数字
美国格式的电话号码格式检查:
// regex.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<regex>
#include<string>
#include<vector>
using namespace std;
bool valid(const smatch& m);
int _tmain(int argc, _TCHAR* argv[])
{
string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
regex r;
try{
r=phone;
}
catch (regex_error e)
{
cout << e.what() << "\ncode: " << e.code() << endl;
}
smatch m;
vector<string> phones;
string s1 = "\(012\)3456789";/*转义字符在搞鬼!:如果是纯写代码的话:写出字符串字面量的时候,(要写成\(
而如果你是从键盘、文件输入进来的话,就直接输入()就可以!*/
string s2="(101) 159 4567";
//cout << "请输入一个美国格式的电话号码:" << endl;/*cin有个问题,遇到空白符(空格 tab 回车)就算结束!*/
//cin >> s2;
/*
valid: (012)3456789
valid: (101) 159 4567
*/
phones.push_back(s1);
phones.push_back(s2);
for (auto & ph : phones)
{
for (sregex_iterator it(ph.begin(), ph.end(), r), end_it; it != end_it; ++it)
{
if (valid(*it))
{
cout << "valid: " << it->str() << endl;
}
else
{
cout << "not valid: " << it->str() << endl;
}
}
}
system("pause");
return 0;
}
bool valid(const smatch& m)
{
/*如果区号前有一个左括号*/
if (m[1].matched)
{/*则区号后必须有一个右括号,之后紧随一个号码数字或者一个空格
所以说:(101) 158 5687 是有效的,而(101).589.6895是无效的!
*/
return m[3].matched && (m[4].matched == 0 || m[4].str() == " ");
}
else
{/*否则,区号后面不能有右括号
另外:分隔符必须一致,用那种就一直用那种,而不能混用!*/
return (!m[3].matched) && (m[4].str() == m[6].str());
}
}
参考资料:
[1]http://www.cplusplus.com/reference/regex/
[2]斯坦利·李普曼, 约瑟·拉乔伊, 芭芭拉·默,等. C++ Primer中文版(第5版)[J]. 中国科技信息, 2013(20):17章:标准库特殊设施
header
<regex>
Regular Expressions
Regular expressions are a standardized way to express patterns to be matched against sequences of characters.
The standard C++ library provides support for regular expressions in the <regex> header through a series of operations. All these operations make use of some typical regex parameters:
- Target sequence (subject): The sequence of characters searched for the pattern. Generally, this is a range specified by two iterators, but some functions also accept a c-string or a string object instead.
- Regular expression (pattern): The pattern which is searched for in the target sequence. This must be an object of a basic_regex type (such as regex), generally constructed from a string with a special syntax that describes what constitutes a match (see ECMAScript syntax).
- Matches array: Some operations allow to retrieve information about matches. This information is stored in one of the special match_results array types (such as cmatch or smatch).
- Replacement string: Some operations can replace matches. These replacements are specified in strings that allow for a special format (see ECMAScript syntax).
Regex operations :
Regex operations are performed using either functions or special iterator adaptors:
Functions:
Match sequence (function template )
Search sequence (function template )
Replace matched sequence (function template )
Iterator types:
Regex iterator (class template )
Regex token iterator (class template )
Classes:
The regex functions and iterators make heavy use of a set of supporting types as arguments and return values:
Basic types:
Regular expression (class template )
Match results (class template )
Sub-expression match (class template )
Regex traits (class template )
Regex exception (class )
Some of these types are templates, and have aliases for their most common instantiations:
basic_regex instantiations:
Regex (class )
Regex for wchar_t (class )
match_results instantiations:
match_results for string literals (class )
match_results for wide string literals (class )
match_results for string objects (class )
match_results for wide string objects (class )
sub_match instantiations:
sub_match for string literals (class )
sub_match for wide string literals (class )
sub_match for strings (class )
sub_match for wide strings (class )
Namespaces
This header also defines a namespace, regex_constants, under which all constant values to be used by the library are located:
regex constants (namespace )
Grammar
Regular expressions follow very strict grammars. By default, the functions in this library use the ECMAScript grammar:
ECMAScript regular expressions pattern syntax (syntax specifications )
Other functions
Iterator to beginning (function template )
Iterator to end (function template )
参考资料
[1][2]斯坦利·李普曼, 约瑟·拉乔伊, 芭芭拉·默,等. C++ Primer中文版(第5版)[J]. 中国科技信息, 2013(20):17章:标准库特殊设施
正则表达式 C++ 字符串匹配替换
[2]链接:https://pan.baidu.com/s/1wFTRB1HoALJhVcNSZlN4Ug 密码:d7zr