Back to index

nordugrid-arc-nox  1.1.0~rc6
ArcRegex.cpp
Go to the documentation of this file.
00001 // -*- indent-tabs-mode: nil -*-
00002 
00003 #ifdef HAVE_CONFIG_H
00004 #include <config.h>
00005 #endif
00006 
00007 #include "ArcRegex.h"
00008 #include <iostream>
00009 
00010 namespace Arc {
00011 
00012   RegularExpression::RegularExpression(std::string pattern)
00013     : pattern(pattern) {
00014     status = regcomp(&preg, pattern.c_str(), REG_EXTENDED);
00015   }
00016 
00017   RegularExpression::RegularExpression(const RegularExpression& regex)
00018     : pattern(regex.pattern) {
00019     status = regcomp(&preg, pattern.c_str(), 0);
00020   }
00021 
00022   RegularExpression::~RegularExpression() {
00023     regfree(&preg);
00024   }
00025 
00026   const RegularExpression& RegularExpression::operator=(const RegularExpression& regex) {
00027     regfree(&preg);
00028     pattern = regex.pattern;
00029     status = regcomp(&preg, pattern.c_str(), 0);
00030     return *this;
00031   }
00032 
00033   bool RegularExpression::isOk() {
00034     return status == 0;
00035   }
00036 
00037   bool RegularExpression::hasPattern(std::string str) {
00038     return pattern == str;
00039   }
00040 
00041   bool RegularExpression::match(const std::string& str) const {
00042     std::list<std::string> unmatched;
00043     std::list<std::string> matched;
00044     return match(str, unmatched, matched) && (unmatched.size() == 0);
00045   }
00046 
00047   bool RegularExpression::match(const std::string& str, std::list<std::string>& unmatched, std::list<std::string>& matched) const {
00048     if (status == 0) {
00049       int st;
00050       regmatch_t rm[256];
00051       unmatched.clear();
00052       st = regexec(&preg, str.c_str(), 256, rm, 0);
00053       if (st != 0)
00054         return false;
00055       regoff_t p = 0;
00056       for (int n = 0; n < 256; ++n) {
00057         if (rm[n].rm_so == -1)
00058           break;
00059         matched.push_back(str.substr(rm[n].rm_so, rm[n].rm_eo - rm[n].rm_so));
00060         if (rm[n].rm_so > p)
00061           unmatched.push_back(str.substr(p, rm[n].rm_so - p));
00062         p = rm[n].rm_eo;
00063       }
00064       if (p < str.length())
00065         unmatched.push_back(str.substr(p));
00066       return true;
00067     }
00068     else
00069       return false;
00070   }
00071 
00072   std::string RegularExpression::getPattern() const {
00073     return pattern;
00074   }
00075 
00076 }