greta使用
GRETA 是 Microsoft Research 的 Eric Niebler 開發的一個 free C++ 正則表達式實現,下載地址 http://research.microsoft.com/projects/greta/ 。 greta主要有如下類:
rpattern 正則表達式類。
match_results 執行結果類
rpattern的主要方法:
- rpattern 構造函數。設置正則表達式和參數。
- match 執行正則表達式。可以接受三種參數:std::string, const char*, const_iterator。返回值為match_results::backref_type。
- subsitute 替換。只能接受 std::string。返回值為替換的數目。
- count 計算正則表達式在串中出現的次數。可以接受和 match 函數一樣的三種參數。
- split 用正則表達式作為分隔符來切分串。也可以接受和 match 一樣的三種參數。
- cgroups 計算正則表達式中包含的組數目。至少為1。
- all_backref 返回 match_results 中的所有 backref 數組。包括組。如果在rpattern 中沒有指定 GLOBAL | ALLBACKREFS 參數,則 all_backref 中最多只會包含 rpattern.cgroups() 個元素;若指定,會包含 rpattern.count() * rpattern.cgroups() 個元素。
- backref 返回 match_results 中指定位置的 backref。包括組。
- cbackrefs 返回 match_results 中 backref 個數。包括組。
- NOCASE 不區分大小寫。
- GLOBAL 全局。如果指定該參數,rpattern::subsitute 會將串中全部匹配表達式的參數替換;否則(默認),若指定了 RIGHTMOST 參數,替換最后一個,沒有指定(默認),替換第一個。
- MULTILINE 若不指定(默認),'^' 匹配串的開頭,'$' 匹配串的結束;若指定,^ 匹配行開頭,$ 匹配行結束。
- SINGLELINE 若不指定(默認),'.' 匹配除換行符(\n)外的任何字符;若指定,'.'也匹配換行符。SINGLELINE 看起來和 MULTILINE 不可一起用,其實她們的含義不是矛盾的,可以一起用。這是 GRETA 的 sb 之處,不知道是否從 perl copy過來的。
- RIGHTMOST 查找最右邊的、最長的匹配串。默認是找左邊的、最長的匹配串。btw, 在正則表達式中加 ? 可以使表達式找最短的匹配串。如串"test",re ".+" 會匹配整個 "test" 串,而 re ".+?" 則只匹配 "t"。
- NOBACKREFS 不記錄 backref 。替換時用上此參數,可大幅度提高速度。這是文檔上說的,俺沒有試過。
- ALLBACKREFS 參見 match_results::all_backref 的解釋。
上面說了 greta 的主要類。下面是如何使用 greta 。 使用 greta ,只要包含 regexpr2.h 這個頭文件即可。(編譯不成功時包含GRETA包中的兩個CPP文件再編譯試試)
==============================================
sample : 匹配 (from greta user's guide)。
match_results results;
string str( "The book cost $12.34" );
rpattern pat( "\\$(\\d+)(\\.(\\d\\d))?" );
// Match a dollar sign followed by one or more digits,
// optionally followed by a period and two more digits.
// The double-escapes are necessary to satisfy the compiler.
match_results::backref_type br = pat.match( str, results );
if( br.matched )
{
??? cout << "match success!" << endl;
??? cout << "price: " << br << endl;
}
else
{
??? cout << "match failed!" << endl;
}
結果為: match success! price: $12.34
轉載于:https://www.cnblogs.com/maifengqiang/archive/2011/05/26/2057747.html
總結
- 上一篇: 在Chrome插件上获取当前插件的版本号
- 下一篇: 面具