A regular expression to exclude a word or character at the start and end of a user inputted answer

Viewed 279

Goal:

I have an answer box that will take inputs from a user. To reduce the amount of possible correct answers I enter into the backend I would like to use a RegExp to ignore certain words/characters at the start and at the end of the answer.

So if the answer was: mountain. I would also accept: the mountain OR a mountain OR the mountains...

What I have tried:

 bool checkAnswer(String answer) {
    List _answers = widget.answers;

    for (var i = 0; i < _answers.length; ++i) {
      // This 
      _correctAnswer = RegExp("?!(the)|(an)|(a)?${widget.answers[i]}s?").hasMatch(answer);
    if (_correctAnswer) {
      return _correctAnswer;
    }
 
    }
    return false;
  }

This function looks at the user input and compares it to the answers I've inputted on the backend. The problem is that it also accepts individual characters 't,h,e'...etc

2 Answers

So you want to remove a leading "the " or "a ", and a trailing plural "s".

Maybe:

bool checkAnswer(String answer, List<String> validAnswers) {
  for (var i = 0; i < validAnswers.length; i++) {
    var re = RegExp("^(?:the | an? )?${validAnswers[i]}s?\$", caseSensitive: false);
    if (re.hasMatch(answer)) return true;
  }
  return false;
}

This checks that string is one of the valid answers, optionally prefixed by the , a or an , and optionally suffixed by s.

The leading ^ and trailing $ (\$ because it's in a non-raw string literal) ensures that the regexp matches the entire input (the ^ matches the beginning of the string and $ matches the end of the string). The | matches either the thing before it or the thing after it (the "alternatives").

If you want to match more different suffixes, say "es" or ".", you change the s? to accept those too:

var re = RegExp("^(?:the | an? )?${validAnswers[i]}(?:e?s)?\\.?\$", caseSensitive: false);

I'm guessing you want to accept s or es and, independently of that, a ..

Your original RegExp was not valid. If it runs at all, I cannot predict what it would do. (For example, a RegExp must not start with ?). I recommend reading a RegExp tutorial.

This is how I ended solving the problem to :

Ignore at the start: the, an, a Ignore at the end: s, es and .

bool checkAnswer(String answer) {
  List _answers = widget.answers;
  for (var i = 0; i < _answers.length; i++) {
    var re = RegExp("^(?:the |an |a )?${_answers[i]}(?:s|es)?.?\$", caseSensitive: false);
    if (re.hasMatch(answer)) return true;
  }
  return false;
}
Related