Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use variables as regular expression value?

For example:

(regexp-match #rx"a|b" "cat")

I would like to bind a variable to "a|b" so that I can create the pattern dynamically.

like image 607
象嘉道 Avatar asked Jan 20 '26 02:01

象嘉道


1 Answers

You can build the pattern dynamically according to your needs (see the documentation), like this:

(regexp "a|b")
> #rx"a|b"

Notice that a pattern is just a string, the regexp procedure takes care of turning it into a regular expression object. The #rx"" notation is just a literal representation of a regex, you can achieve the same effect by using the regexp procedure. After that, the regular expression can be bound to a variable:

(let ((regexp (regexp "a|b")))
  (regexp-match regexp "cat"))

Or used as a procedure parameter:

(define (matcher regexp)
  (regexp-match regexp "cat"))

(matcher (regexp "a|b"))

Or any other way you fancy.

like image 193
Óscar López Avatar answered Jan 21 '26 20:01

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!