2009年1月12日 星期一

利用正規表達式(Regular Expression)做E-mail驗證

利用正規表達式(Regular Expression)做E-mail驗證
#include <iostream>
#include <string>
#include <regex>
using namespace std;
using namespace std::tr1;
int main(int argc, char *argv[]) {
  string email("ecjcoqofvn@mailinator.com.tw");
  if(0 == email.size()) {
    cout << "Please Keyin Your Email : ";
    cin >> email;
  }
  regex rx("^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+$");
  if(regex_match(email, rx)) {
    cout << "E-mail Validate : OK" << endl;
    smatch res;
    if(regex_search(email, res, rx)) {
      cout << "E-mail : " << res[1] << endl;
      cout << "User Name : " << res[2] << endl;
      cout << "Host Name : " << res[3] << endl;
      if(0 != (string(res[4])).size()) {
        cout << "." << res[4] << endl;
      }
    }
  } else {
    cout << "E-mail Validate : Error" << endl;
  }
  system("pause");
  return EXIT_SUCCESS;
}
#include <iostream>
#include <string>
#include <regex>
using namespace std;
using namespace std::tr1;
int main(int argc, char *argv[]) {
  string ss("xyz1 xyz2 xyz3 xyz4");
  regex rx("((xyz)(\\d))");
  /*------------------------------------------------------------*/
  cout << "sregex_token_iterator" << endl;
  sregex_token_iterator itrBegin2(ss.begin(), ss.end(), rx), itrEnd2;
  copy(itrBegin2, itrEnd2, ostream_iterator<string>(cout, "\n"));
  cout << endl;
  /*------------------------------------------------------------*/
  cout << "sregex_iterator" << endl;
  sregex_iterator itrBegin(ss.begin(), ss.end(), rx), itrEnd;
  for(sregex_iterator itr = itrBegin; itr != itrEnd; ++itr) {
    for(unsigned int cou = 0; cou < itr->size(); ++cou) {
      cout << itr->str(cou) << ",";
    }
    cout << endl;
  }
  system("pause");
  return EXIT_SUCCESS;
}

沒有留言:

張貼留言