Fix what looks like an off-by-one error in RegEx::longestMatch()'s lastMatch calculation, and a corresponding +1 in code using longestMatch, and add a test.
This commit is contained in:
@@ -21,9 +21,10 @@ class RegEx {
|
||||
int longMatch(std::string stringToMatch);
|
||||
std::string getPattern();
|
||||
std::string toString();
|
||||
static void test();
|
||||
private:
|
||||
std::string pattern;
|
||||
RegExState* begin;
|
||||
std::vector<RegExState*> currentStates;
|
||||
};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
1
main.cpp
1
main.cpp
@@ -19,6 +19,7 @@
|
||||
int main(int argc, char* argv[]) {
|
||||
if (argc == 2 && std::string(argv[1]) == "--test") {
|
||||
StringReader::test();
|
||||
RegEx::test();
|
||||
Lexer::test();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@ Symbol Lexer::next() {
|
||||
}
|
||||
}
|
||||
if (longestRegEx != NULL) {
|
||||
std::string eatenString = input.substr(currentPosition, longestMatch+1);
|
||||
currentPosition += longestMatch + 1;
|
||||
std::string eatenString = input.substr(currentPosition, longestMatch);
|
||||
currentPosition += longestMatch;
|
||||
//std::cout << "Current at is \"" << input.substr(currentPosition,input.length()-1) << "\" currentPos is " << currentPosition <<std::endl;
|
||||
return Symbol(longestRegEx->getPattern(), true, eatenString);
|
||||
} else {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "RegEx.h"
|
||||
#include <cassert>
|
||||
|
||||
RegEx::RegEx(std::string inPattern) {
|
||||
pattern = inPattern;
|
||||
@@ -242,7 +243,7 @@ int RegEx::longMatch(std::string stringToMatch) {
|
||||
//Also, add each state's advance to nextStates
|
||||
for (std::vector<RegExState*>::size_type j = 0; j < currentStates.size(); j++) {
|
||||
if (currentStates[j]->isGoal()) {
|
||||
lastMatch = i-1;
|
||||
lastMatch = i;
|
||||
//std::cout << "Hit goal at " << i << " character: " << stringToMatch[i-1] << std::endl;
|
||||
} else {
|
||||
//std::cout << "currentState " << j << ", " << currentStates[j]->toString() << " is not goal" <<std::endl;
|
||||
@@ -274,7 +275,7 @@ int RegEx::longMatch(std::string stringToMatch) {
|
||||
//Check to see if we match on the last character in the string
|
||||
for (std::vector<RegExState*>::size_type j = 0; j < currentStates.size(); j++) {
|
||||
if (currentStates[j]->isGoal())
|
||||
lastMatch = stringToMatch.size()-1;
|
||||
lastMatch = stringToMatch.size();
|
||||
}
|
||||
return lastMatch;
|
||||
}
|
||||
@@ -286,3 +287,12 @@ std::string RegEx::getPattern() {
|
||||
std::string RegEx::toString() {
|
||||
return pattern + " -> " + begin->toString();
|
||||
}
|
||||
|
||||
void RegEx::test() {
|
||||
{
|
||||
RegEx re("a*");
|
||||
assert(re.longMatch("aa") == 2);
|
||||
}
|
||||
|
||||
std::cout << "RegEx tests pass\n";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user