Skip to content

Instantly share code, notes, and snippets.

@r2p2
Last active December 15, 2015 20:29
Show Gist options
  • Select an option

  • Save r2p2/5318764 to your computer and use it in GitHub Desktop.

Select an option

Save r2p2/5318764 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <string>
class Finder
{
public:
Finder()
: _pattern()
, _start(false)
, _end(false)
{}
void pattern(const std::string &pattern)
{
if(not pattern.empty() and pattern[0] == '*')
_start = true;
if(not pattern.empty() and pattern[pattern.size()-1] == '*')
_end = true;
size_t search_start_pos = 0;
while(search_start_pos < pattern.size())
{
const size_t found_pos = pattern.find("*", search_start_pos);
if(found_pos == std::string::npos)
{
_pattern.push_back(pattern.substr(search_start_pos));
return;
}
const size_t pattern_size = found_pos - search_start_pos;
if(pattern_size > 0)
_pattern.push_back(pattern.substr(search_start_pos, pattern_size));
search_start_pos = found_pos + 1;
}
}
std::string match(const std::string &data)
{
size_t start_pos = 0;
size_t end_pos = 0;
for(std::vector<std::string>::const_iterator it = _pattern.begin();
it != _pattern.end(); ++it)
{
const std::string &pattern = *it;
const size_t found_pos = data.find(pattern, end_pos);
if(found_pos == std::string::npos)
{
end_pos = start_pos = 0;
break;
}
if(it == _pattern.begin())
start_pos = found_pos;
end_pos = found_pos + pattern.size();
}
if(_start)
start_pos = 0;
if(_end)
end_pos = data.size();
return data.substr(start_pos, end_pos - start_pos);
}
private:
std::vector<std::string> _pattern;
bool _start;
bool _end;
};
bool test(const std::string &pattern, const std::string &data, const std::string &expected)
{
Finder f;
f.pattern(pattern);
const std::string result = f.match(data);
if(result != expected)
{
std::cout << "ERROR P:'" << pattern << "' D:'" << data << "' => '" << result << "'" << std::endl;
return false;
}
return true;
}
int main()
{
test("", "abc", "");
test("*", "abc", "abc");
test("**", "abc", "abc");
test("abc", "abc", "abc");
test("b", "abc", "b");
test("b*", "abc", "bc");
test("*b", "abc", "ab");
test("*b*", "abc", "abc");
test("a*c", "abc", "abc");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment