[racket] Regexp: Ways to reduce number of list elements returned?
I've taken to using `match` for this. Your example:
(regexp-match #rx"\"(.*)" "a\"b")
I would write as:
(match "a\"b"
[(regexp "\"(.*)" (list _ x)) x])
; "b"
Handling the no-match case by returning #f:
(match "ab"
[(regexp "\"(.*)" (list _ x)) x]
[_ #f])
; #f
Laurent's approach of defining a function works well, too. But I often
find myself matching multiple items, and use the list to bind to
multiple variables:
(match "x=y"
[(pregexp "(.+)\\s*=\\s*(.+)" (list _ k v)) (values k v)]
[_ #f])
; "x"
; "y"
So I like match as it works in the general case.
Note that there's `pregexp` as well as `regexp`, like I used here.
On Fri, May 10, 2013 at 11:27 AM, Don Green <infodeveloperdon at gmail.com> wrote:
> Regexp question:
> Is there a way using regexp only to return a list with a single element?
> I could use a Racket list function such as caar to return the second element
> but I am wondering if there is a way to do this using regexp only.
>
> For example this regexp-match function generates the "b" that I want but it
> is the second element in the list. It would be ideal, from my perspective,
> if that was all it generated. Is there a way to write the regexp-match
> expression so that '("b") is output?
>
> I get this:
> (regexp-match #rx"\"(.*)" "a\"b") ; => '("\"b" "b")
>
> I'd prefer:
> (regexp... "a\"b" ) ; => '("b")
>
> Thanks.
> Don Green
>
> ____________________
> Racket Users list:
> http://lists.racket-lang.org/users
>