[C/C++]_[初級]_[正則表示式的反向引用]
阿新 • • 發佈:2018-12-01
場景
1.正則表示式查詢特定規則的字串十分高效率, 有一些規則的字串, 如果不用正則, 單是列舉+邏輯記錄匹配的程式碼量就非常大.
2.比如查詢一個小寫字串裡連續相同的字母, 之後把它替換為 Xn(大寫字母和重複字母個數)的方式進行加密. 正好正則表示式有專門的反向引用來解決查詢重複字元的問題.
例子
void TestBackreference()
{
std::string line = "trellis lLlama webbing dresser swagger";
std::regex pattern("(\\w)\\1+",std::regex_constants::icase);
std ::smatch word_match;
while (std::regex_search(line, word_match, pattern)) {
std::cout << word_match.str() << '\n';
line = word_match.suffix();
}
}
輸出
ll
lLl
bb
ss
gg
參考
regular-expression-language-quick-reference
backreference-constructs-in-regular-expressions
how-can-i-find-repeated-letters-with-a-perl-regex