正規表現of c++

18079 ワード

#include "mystring.h"
#include
#include
/*
 *       of c++
*/
using namespace std;

int main(){
    regex pattern(".*(lo\\w{1,}).*",regex::icase);//()          ,  0 str,1          
    smatch result;
    string str="i love the world";

    //1.use way one :regex_match=====this all pattern return true
    if(regex_match(str,result,pattern)){
        for (auto it=result.begin();it<result.end();it++) {
            cout<<*it<<endl;
        }
    }

    //2.use way two:regex_search=======  ()           ,    1 love,
     regex pattern2("(\\blove\\b).*",regex::icase);
     if(regex_search(str,result,pattern2)){
         for (auto it=result.begin();it<result.end();it++) {
             cout<<*it<<endl;
         }
    }

    //3.use way three:regex_replace======
    regex pattern3("\\blove\\b",regex::icase);
    str=regex_replace(str,pattern3,"hate");
    cout<<str.c_str()<<endl;
    return 0;
}
/*
 * result:
i love the world
love

love the world
love

i hate the world

*/

string replaceAll(string& base, const string src, const string dst){
    unsigned long pos = 0;
    while (((pos = base.find(src, pos)) != string::npos)){
        base.replace(pos, src.size(), dst);
        pos += dst.size();
    }
    return base;
}
void MyString::split(const std::string& all_str, std::vector<std::string>& vec, const std::string& c){
     string::size_type pos1, pos2;
     size_t len = all_str.length();
     pos2 = all_str.find(c);
     pos1 = 0;
     while(string::npos != pos2){
         vec.emplace_back(all_str.substr(pos1, pos2-pos1));
         pos1 = pos2 + c.size();
         pos2 = all_str.find(c, pos1);
     }
     if(pos1 != len)
         vec.emplace_back(all_str.substr(pos1));
}

string strip(string const & s, char c = ' ') {  
  string::size_type a = s.find_first_not_of(c);  
  string::size_type z = s.find_last_not_of(c);  
  if(a == string::npos){  
    a = 0;  
  }  
  
  if(z == string::npos){  
    z = s.size();  
  }  
  return s.substr(a, z);  
}  
void spliteFilePath(string all_name,string& file_name,string& dir_name){
    std::regex pattern("\\\\{1,}");
    all_name=std::regex_replace(all_name,pattern,"/");
    pattern=string("/{1,}");
    all_name=std::regex_replace(all_name,pattern,"/");
    dir_name=all_name.substr(0,all_name.find_last_of("/")+1);
    file_name=all_name.substr(all_name.find_last_of("/")+1);
}