03f0f79d3eb75a315e54c164497556ec7424d5c8
[platform/upstream/libzypp.git] / zypp / base / Regex.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/base/Regex.cc
10  *
11 */
12 #include <cstdio>
13 #include <cstdarg>
14
15 #include <iostream>
16
17 #include "zypp/base/Regex.h"
18
19 using namespace zypp::str;
20
21 regex::regex(const std::string& str, int flags)
22 {
23     m_valid = true;
24     if (regcomp(&m_preg, str.c_str(), REG_EXTENDED))
25         m_valid = false;
26 }
27
28 regex::~regex() throw()
29 {
30     if (m_valid)
31         regfree(&m_preg);
32 }
33
34 bool zypp::str::regex_match(const std::string& s, smatch& matches, const regex& regex)
35 {
36     bool r = regex.m_valid && !regexec(&regex.m_preg, s.c_str(), 12, &matches.pmatch[0], 0);
37     if (r)
38         matches.match_str = s;
39     return r;
40 }
41
42 bool zypp::str::regex_match(const std::string& s,  const regex& regex)
43 {
44     return !regexec(&regex.m_preg, s.c_str(), 0, NULL, 0);
45 }
46
47 bool zypp::str::regex_search(const std::string& s, smatch& matches, const regex& regex)
48 {
49     bool r= regex.m_valid && !regexec(&regex.m_preg, s.c_str(), 12, &matches.pmatch[0], 0);
50     if (r)
51         matches.match_str = s;
52     return r;
53 }
54
55 smatch::smatch()
56 {
57     memset(&pmatch, -1, sizeof(pmatch));
58 }
59
60 std::string smatch::operator[](unsigned i) const 
61 {
62     if (i < 12 && pmatch[i].rm_so != -1)
63         return match_str.substr(pmatch[i].rm_so, pmatch[i].rm_eo-pmatch[i].rm_so);
64     return std::string();
65 }
66
67
68 unsigned smatch::size() const
69 {
70     unsigned matches = 0;
71     while (matches < 12 && pmatch[matches+1].rm_so != -1) {
72     //    std::cout << "match[" << matches << "]: *" << (*this)[matches
73     //        +1] << "*" << std::endl;
74         matches++;
75     }
76
77     return matches;
78 }