3
\$\begingroup\$

I've written an algebraic notation to use for moves in a game and I'm currently writing code to parse the information from the notation. I'm doing this using regExes. This is coded in HaXe.

For example, two functions in the parser would look like this:

public function getMoveType(gameText:String):String
{
   var moveTypeRegEx:EReg = ~/MatchThis/;
   moveTypeRegEx.match(gameText);
   var moveType:String = moveTypeRegEx.matched(0); //this returns entire string that was matched.
   return moveType;
}

public function getPlayerName(gameText:String):String
{
    var playerNameRegEx:EReg = ~/MatchThis/;
    playerNameRegEx.match(gameText);
    var playerName:String = playerNameRegEx.matched(0);
    return playerName;
}
  1. How could this be written better to make it more readable or more organized?
  2. Would it be better to have a class file GameRegExes, which contains all the regexes I need with getter functions to those regexes?

Please let me know if I'm being too vague.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The use of regular expressions is an implementation detail.

I think you should continue to structure your API as functions that take a higher level input, such as a game text, and destructure it into the end product that your API's clients want.

That said, you can define a private helper that takes a regular expression and does the work of matching the text and extracting group 0. Then each of your public functions would delegate most of the work to that just providing it with the appropriate regular expression and maybe the index of the group to return.

private function gameTextExtractor(gameText:String, regex:EReg):String
{
    regex.match(gameText);
    return regex.matched(0);
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.