Migrating from Python to Racket (regex libraries and the "Racket Way")

I am trying to learn Racket, and in the process I am trying to rewrite the Python filter. There are two pairs of functions in my code:

def dlv(text): """ Returns True if the given text corresponds to the output of DLV and False otherwise. """ return text.startswith("DLV") or \ text.startswith("{") or \ text.startswith("Best model") def answer_sets(text): """ Returns a list comprised of all of the answer sets in the given text. """ if dlv(text): # In the case where we are processing the output of DLV, each # answer set is a comma-delimited sequence of literals enclosed # in {} regex = re.compile(r'\{(.*?)\}', re.MULTILINE) else: # Otherwise we assume that the answer sets were generated by # one of the Potassco solvers. In this case, each answer set # is presented as a comma-delimited sequence of literals, # terminated by a period, and prefixed by a string of the form # "Answer: #" where "#" denotes the number of the answer set. regex = re.compile(r'Answer: \d+\n(.*)', re.MULTILINE) return regex.findall(text) 

From what I can say, the implementation of the first function in Racket will be something like the following lines:

 (define (dlv-input? text) (regexp-match? #rx"^DLV|^{|^Best model" text)) 

It seems to work correctly. While working on the implementation of the second function, currently I have come up with the following (for starters):

 (define (answer-sets text) (cond [(dlv-input? text) (regexp-match* #rx"{(.*?)}" text)])) 

This is not true since regexp-match* gives a list of strings that match the regular expression, including curly braces. Does anyone know how to achieve the same behavior as in a Python implementation? In addition, any suggestions on how to make regular expressions โ€œbetterโ€ would be greatly appreciated.

+7
source share
1 answer

You are very close. You just need to add #:match-select cadr to your regexp-match call:

 (regexp-match* #rx"{(.*?)}" text #:match-select cadr) 

By default, #:match-select is set to car , which returns an entire string. cadr selects the first group, caddr selects the second group, etc. See the regexp-match* documentation for more details.

+8
source

All Articles