1. 程式人生 > >c++正則簡單例項

c++正則簡單例項

#include <iostream>
#include <string>
#include <regex>

using namespace std;

void testRegx() {
    regex regx("h(.+?)llo",regex::icase);
    string str = "hello world!hollo world....hallo1  heello2";

    bool remr = regex_match(str, regx);//regex_match全字串匹配
    if (remr) {
        cout
<< "matched" << endl; }else { cout << "not matched" << endl; } smatch mch; string newStr = str; while (regex_search(newStr, mch, regx)) {//regex_search查詢子字串 cout << "searched:" << mch.str() << endl; newStr = mch.suffix().str(); } std
::cout << std::regex_replace(str, regx, "hi-$1") << endl;;//替換子字串 cout << str << endl; } int main() { testRegx(); return 0; }

輸出結果:

not matched
searched:hello
searched:hollo
searched:hallo
searched:heello
hi-e world!hi-o world....hi-a1  hi-ee2
hello world!hollo world...
.hallo1 heello2 請按任意鍵繼續. . .