-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregex.cpp
More file actions
108 lines (98 loc) · 2.64 KB
/
regex.cpp
File metadata and controls
108 lines (98 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// (ha+)+
// s -> h J
// J -> a s | a J | a
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
class RegexHa
{
private:
using u32 = uint32_t;
u32 m_CurPos = 0u;
bool m_ParseSuccess = false;
std::string m_InputString;
std::string m_ErrorMsg;
bool match(char const& lCharToMatch)
{
if((m_CurPos < m_InputString.size()) and (lCharToMatch == m_InputString[m_CurPos]))
{
++m_CurPos;
return true;
}
return false;
}
bool ruleS()
{
if(match('h'))
return ruleJ();
return false;
}
bool ruleJ()
{
if(match('a'))
{
if(m_CurPos == m_InputString.size())
return true;
else if(ruleS())
return true;
else if(ruleJ())
return true;
else
return false;
}
return false;
}
bool parse()
{
m_ParseSuccess = ('h' == m_InputString.front()) and ('a' == m_InputString.back());
if (not m_ParseSuccess)
{
m_ErrorMsg =
"unexpected tokens at the start/end of input string parsing "
"stopped, expected \"h\" at start and \"a\" at the end";
return false;
}
m_ParseSuccess = ruleS() and (m_CurPos == m_InputString.size());
if (not m_ParseSuccess)
{
if (m_CurPos < m_InputString.size())
m_ErrorMsg =
"parsing failed at position: " + std::to_string(m_CurPos) +
" (expected more input)";
else
m_ErrorMsg = "parsing failed: unexpected end of input";
}
return m_ParseSuccess;
}
public:
bool parse(std::string const& lStringToParse)
{
m_InputString = lStringToParse;
return parse();
}
bool parse(std::string&& lStringToParse)
{
m_InputString = std::move(lStringToParse);
return parse();
}
friend std::ostream& operator<<(std::ostream &lOutStream, RegexHa const& lRegex)
{
lOutStream << std::quoted(lRegex.m_InputString) << ' ';
if(lRegex.m_ParseSuccess)
lOutStream << "parsed with success";
else
lOutStream << lRegex.m_ErrorMsg;
return lOutStream;
}
};
int main(void)
{
std::string lTestCases[] = {"ha", "haha", "hahaha", "hahaaa", "haah", "ah", "h", "haahahhaa"};
for(const auto &lStringToCheck : lTestCases)
{
RegexHa lRegex;
std::cout << std::boolalpha << lRegex.parse(lStringToCheck) << ' ' << lRegex << '\n';
}
return 0;
}