match函数无法匹配我的字符串
(define str "abc captain:10 others:30 first-officer:20 alt:40")
(match (string->list str)
;;method 1
[(list _ ... #\i #\n #\: cap ... #\space _ ... #\e #\r #\: fst ... #\space _ ...)
;;method 2
;; [(list _ ... #\i #\n #\: cap ..2 #\space _ ... #\e #\r #\: fst ... #\space _ ...)
(list (list->string cap) (list->string fst))])
运行上述代码时,我得到
'("10 others:30" "20")
我想取出紧跟在字符串 captain 与 first-officer 之后的数字。两种方法我都尝试过,但都失败了。
为什么会这样,以及该如何让它正确工作?
解决方案
像你现在这样使用 match 和一大串字符列表,真的很尴尬、笨拙,而且不符合惯用写法。不要这么做。未来的你会感谢现在的自己。
Regular expressions 要合适得多:
#lang racket/base
(require racket/list) ; for third
(define str "abc captain:10 others:30 first-officer:20 alt:40")
(println
(regexp-match* #px"\\b(captain|first-officer):(\\d+)" str #:match-select third))
; => '("10" "20")
你可以通过调整 #:match-select 参数来使用 regexp-match* 来获得实际期望的结果;例如使用 rest(或 cdr)来代替,将得到 '(("captain" "10") ("first-officer" "20")),它可以与 alist 等函数一起使用,如 assoc。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。