VC正則表達式的使用
正則表達式是一種對字符進行模糊匹配的一個公式。在數據有效性驗證,查找,替換文本中都可以使用正則表達式 。
本篇文章主要描述的是使用ATL中兩個模板類CAtlRegExp和CAtlREMatchContext。
在使用CAtlRegExp類之前需要添加#include <atlrx.h> 這個頭文件。
RegExp是Regular Expression的縮寫
以匹配郵件地址字符串爲例說明兩個類的使用
該示例更改自http://msdn.microsoft.com/en-us/library/k3zs4axe(VS.80).aspx
CString strRegex=L"({[0-9_]+@[a-zA-Z0-9]+[.][a-zA-Z0-9]+[.]?[a-zA-Z0-9]+})";
CString strInput;
strInput=L"[email protected]";
CAtlRegExp<CAtlRECharTraitsW> reRule;
wchar_t *wt = (wchar_t *)(LPCTSTR)strRegex;
REParseError status = reRule.Parse((const ATL::CAtlRegExp<CAtlRECharTraitsW>::RECHAR *)wt);
if (REPARSE_ERROR_OK != status)
{
return 0;
}
CAtlREMatchContext<CAtlRECharTraitsW> mcRule;
wt = (wchar_t *)(LPCTSTR)strInput;
if (!reRule.Match((const ATL::CAtlRegExp<CAtlRECharTraitsW>::RECHAR *)wt,&mcRule))
{
AfxMessageBox(L"您輸入的郵件地址不合法!");
}
else
{
for (UINT nGroupIndex = 0; nGroupIndex < mcRule.m_uNumGroups; ++nGroupIndex)
{
const CAtlREMatchContext<>::RECHAR* szStart = 0;
const CAtlREMatchContext<>::RECHAR* szEnd = 0;
mcRule.GetMatch(nGroupIndex, &szStart, &szEnd);
ptrdiff_t nLength = szEnd - szStart;
CString strEmailAddress(szStart, static_cast<int>(nLength));
if(strEmailAddress.Compare(strInput)!=0)
{
CString strPrompt;
strPrompt.Format(L"您輸入的郵件地址不合法,您要輸入%s 嗎!",strEmailAddress);
AfxMessageBox(strPrompt);
}
else
{
AfxMessageBox(L"輸入的郵件地址正確!");
}
}
}
這兩個模板類由另一個描述字符集特性的類參數化,可以是ASCII,WCHAR 或多字節。
可以將此忽略掉,因爲根據設置的字符集,模板類自動生成具體的類。
在atlrx.h文件中供選擇的有三個類
CAtlRECharTraitsA 用於ASCII
CAtlRECharTraitsW 用於UNICODE
CAtlRECharTraitsMB 用於多字節
在VC2005默認的字符集是使用Unicode字符集
根據正則的源碼
#ifndef _UNICODE
typedef CAtlRECharTraitsA CAtlRECharTraits;
#else // _UNICODE
typedef CAtlRECharTraitsW CAtlRECharTraits;
#endif // !_UNICODE
所以構造CAtlRegExp類可以是
CAtlRegExp<> reRule;
REParseError status = reRule.Parse((const ATL::CAtlRegExp<CAtlRECharTraitsW>::RECHAR *)wt);
也可以是
CAtlRegExp<CAtlRECharTraitsW> reRule;
REParseError status = reRule.Parse((const ATL::CAtlRegExp<CAtlRECharTraitsW>::RECHAR *)wt);
通過調用CAtlRegExp的Parse()方法,使用正則表達式字符串作爲參數,就可以構造出一個我們所需要的類。
調用CATLRegExp的Match()函數
Match()函數參數說明
第一個參數是要對比的字符串,
第二個參數是存儲match的結果
CAtlREMatchContext的成員變量m_uNumGroups表示匹配的Group
CAtlREMatchContext的GetMatch()函數返回匹配上的字符串的pStart和pEnd指針
以下從MSDN摘錄的正則表達語法
原文是http://msdn.microsoft.com/en-us/library/k3zs4axe(VS.80).aspx
Regular Expression Syntax
This table lists the metacharacters understood by CAtlRegExp.
Metacharacter |
Meaning |
. |
Matches any single character. |
[ ] |
Indicates a character class. Matches any character inside the brackets (for example, [abc] matches "a", "b", and "c"). |
^ |
If this metacharacter occurs at the start of a character class, it negates the character class. A negated character class matches any character except those inside the brackets (for example, [^abc] matches all characters except "a", "b", and "c"). If ^ is at the beginning of the regular expression, it matches the beginning of the input (for example, ^[abc] will only match input that begins with "a", "b", or "c"). |
- |
In a character class, indicates a range of characters (for example, [0-9] matches any of the digits "0" through "9"). |
? |
Indicates that the preceding expression is optional: it matches once or not at all (for example, [0-9][0-9]? matches "2" and "12"). |
+ |
Indicates that the preceding expression matches one or more times (for example, [0-9]+ matches "1", "13", "456", and so on). |
* |
Indicates that the preceding expression matches zero or more times. |
??, +?, *? |
Non-greedy versions of ?, +, and *. These match as little as possible, unlike the greedy versions that match as much as possible (for example, given the input "<abc><def>", <.*?> matches "<abc>" while <.*> matches "<abc><def>"). |
( ) |
Grouping operator. Example: (/d+,)*/d+ matches a list of numbers separated by commas (for example, "1" or "1,23,456"). |
{ } |
Indicates a match group. The actual text in the input that matches the expression inside the braces can be retrieved through theCAtlREMatchContext object. |
/ |
Escape character: interpret the next character literally (for example, [0-9]+ matches one or more digits, but [0-9]/+ matches a digit followed by a plus character). Also used for abbreviations (such as /a for any alphanumeric character; see the following table). If / is followed by a number n, it matches the nth match group (starting from 0). Example: <{.*?}>.*?<//0> matches "<head>Contents</head>". Note that, in C++ string literals, two backslashes must be used: "//+", "//a", "<{.*?}>.*?<///0>". |
$ |
At the end of a regular expression, this character matches the end of the input (for example,[0-9]$ matches a digit at the end of the input). |
| |
Alternation operator: separates two expressions, exactly one of which matches (for example, T|the matches "The" or "the"). |
! |
Negation operator: the expression following ! does not match the input (for example, a!b matches "a" not followed by "b"). |
Abbreviations
CAtlRegExp can handle abbreviations, such as /d instead of [0-9]. The abbreviations are provided by the character traits class passed in the CharTraits parameter. The predefined character traits classes provide the following abbreviations.
Abbreviation |
Matches |
/a |
Any alphanumeric character: ([a-zA-Z0-9]) |
/b |
White space (blank): ([ //t]) |
/c |
Any alphabetic character: ([a-zA-Z]) |
/d |
Any decimal digit: ([0-9]) |
/h |
Any hexadecimal digit: ([0-9a-fA-F]) |
/n |
Newline: (/r|(/r?/n)) |
/q |
A quoted string: (/"[^/"]*/")|(/'[^/']*/') |
/w |
A simple word: ([a-zA-Z]+) |
/z |
An integer: ([0-9]+) |
關於語法翻譯可參考http://www.vckbase.com/document/viewdoc/?id=1138
摘錄
字符元 |
意義 |
. |
匹配單個字符 |
[ ] |
指定一個字符類,匹配方括號內的任意字符。例:[abc] 匹配 "a", "b"或 "c"。 |
^ |
如果^出現在字符類的開始處,它否定了字符類,這個被否定的字符類匹配除卻方括號內的字符的字符。如:[^abc]匹配除了"a", "b"和"c"之外的字符。如果^出現在正則表達式前邊,它匹配輸入的開頭,例:^[abc]匹配以"a", "b"或"c"開頭的輸入。 |
- |
在字符類中,指定一個字符的範圍。例如:[0-9]匹配"0"到"9"的數字。 |
? |
指明?前的表達式是可選的,它可以匹配一次或不進行匹配。例如: [0-9][0-9]? 匹配"2"或"12"。 |
+ |
指明?前的表達式匹配一次或多次。例如:[0-9]+匹配"1", "13", "666"等。 |
* |
指明*前的表達式匹配零次或多次。 |
??, +?, *? |
?, +和*的非貪婪匹配版本,它們儘可能匹配較少的字符;而?, +和*則是貪婪版本,儘可能匹配較多的字符。例如:輸入"<abc><def>", 則<.*?> 匹配"<abc>",而<.*>匹配"<abc><def>"。 |
( ) |
分組操作符。例如:(/d+,)*/d+匹配一串由逗號分開的數字,例如: "1"或"1,23,456"。 |
/ |
轉義字符,轉義緊跟的字符。例如,[0-9]+ 匹配一個或多個數字,而 [0-9]/+ 匹配一個數字後跟隨一個加號的情況。反斜槓/也用於表示縮寫,/a 就表示任何數字、字母。如果/後緊跟一個數字n,則它匹配第n個匹配羣組(從0開始),例如,<{.*?}>.*?<//0>匹配"<head>Contents</head>"。注意,在C++字符串中,反斜槓/需要用雙反斜槓//來表示: "//+", "//a", "<{.*?}>.*?<///0>"。 |
$ |
放在正則表達式的最後,它匹配輸入的末端。例如:[0-9]$匹配輸入的最後一個數字。 |
| |
間隔符,分隔兩個表達式,以正確匹配其中一個,例如:T|the匹配"The" 或"the"。 |
對“^”的強調:
如果^出現在字符類的開始處,它否定了字符類,例:[^abc]匹配除了"a", "b"和"c"之外的字符
如果^出現在正則表達式前邊,它匹配輸入的開頭,例:^[abc]匹配以"a", "b"或"c"開頭的輸入
對“$”的強調:
出現在末尾,表示結束。
縮寫匹配
縮寫 |
匹配 |
/a |
字母、數字([a-zA-Z0-9]) |
/b |
空格(blank): ([ //t]) |
/c |
字母([a-zA-Z]) |
/d |
十進制數 ([0-9]) |
/h |
十六進制數([0-9a-fA-F]) |
/n |
換行: (/r|(/r?/n)) |
/q |
引用字符串(/"[^/"]*/")|(/''''[^/'''']*/'''') |
/w |
一段文字 ([a-zA-Z]+) |
/z |
一個整數([0-9]+) |
正則表達式語法
字符元 意義 . 匹配單個字符 [ ] 指定一個字符類,匹配方括號內的任意字符。例:[abc] 匹配 "a", "b"或 "c"。 ^ 如果^出現在字符類的開始處,它否定了字符類,這個被否定的字符類匹配除卻方括號內的字符的字符。如:[^abc]匹配除了"a", "b"和"c"之外的字符。如果^出現在正則表達式前邊,它匹配輸入的開頭,例:^[abc]匹配以"a", "b"或"c"開頭的輸入。 - 在字符類中,指定一個字符的範圍。例如:[0-9]匹配"0"到"9"的數字。 ? 指明?前的表達式是可選的,它可以匹配一次或不進行匹配。例如: [0-9][0-9]? 匹配"2"或"12"。 + 指明?前的表達式匹配一次或多次。例如:[0-9]+匹配"1", "13", "666"等。*
指明*前的表達式匹配零次或多次。 ??, +?, *? ?, +和*的非貪婪匹配版本,它們儘可能匹配較少的字符;而?, +和*則是貪婪版本,儘可能匹配較多的字符。例如:輸入"<abc><def>", 則<.*?> 匹配"<abc>",而<.*>匹配"<abc><def>"。 ( ) 分組操作符。例如:(d+,)*d+匹配一串由逗號分開的數字,例如: "1"或"1,23,456"。 轉 義字符,轉義緊跟的字符。例如,[0-9]+ 匹配一個或多個數字,而 [0-9]+ 匹配一個數字後跟隨一個加號的情況。反斜槓也用於表示縮寫,a 就表示任何數字、字母。如果後緊跟一個數字n,則它匹配第n個匹配羣組(從0開始),例如,<{.*?}>.*?</>匹配 "<head>Contents</head>"。注意,在C++字符串中,反斜槓需要用雙反斜槓來表示: "+", "a", "<{.*?}>.*?</ >"。 $ 放在正則表達式的最後,它匹配輸入的末端。例如:[0-9]$匹配輸入的最後一個數字。 | 間隔符,分隔兩個表達式,以正確匹配其中一個,例如:T|the匹配"The" 或"the"。
縮寫匹配
縮寫 匹配 a 字母、數字([a-zA-Z0-9]) 空格(blank): ([ ]) c 字母([a-zA-Z]) d 十進制數 ([0-9]) h 十六進制數([0-9a-fA-F]) 換行: ( |( ? )) q 引用字符串("[^"]*")|(''''[^'''']*'''') w 一段文字 ([a-zA-Z]+) z 一個整數([0-9]+)ATL CATLRegExp
ATL Server常常需要對地址、命令等複雜文字字段信息解碼,而正則表達式是強大的文字解析工具,所以,ATL提供了正則表達式解釋工具。
其他:
頭文件不存在的問題:
VS 2008中由於將ALT項目的部分代碼剝離出去成爲了獨立的開源項目,需要用到ALT中正則表達式等功能就需要手動下載。
參考:http:
//connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=306398
下載地址:http:
//www.codeplex.com/AtlServer
把下載的東西解壓縮到一個目錄,比如c:\alt\
在VS裏面[工具]--[選項]--[項目和解決方案]--[VC++目錄],在右上角選擇[包含引用的文件]中加入c:\alt\include就OK了
還有一個值得注意的地方就是ATL中用大括號"({})"表示其子匹配
子匹配Group從0開始.
例如:
re.Parse("^{\\w+}\\b+{(\\a|\\b)+}$");
// {} 表示要保存到匹配結果MathContext中,等同於PERL的()
// () 表示把集合,等同於PERL的[]
參考:
http://blog.csdn.net/abcpanpeng/article/details/4461836
http://blog.csdn.net/whucv/article/details/7880796
http://blog.sina.com.cn/s/blog_4840fe2a0100rbsq.html
http://blog.csdn.net/wu_huiwen/article/details/5523128
http://tool.chinaz.com/regex
http://www.cnblogs.com/deerchao/archive/2006/08/24/zhengzhe30fengzhongjiaocheng.html
http://www.vckbase.com/index.php/wv/1351