我是Racket的新手,但对此非常兴奋。我一直在为WWW-Authenticate标题编写一个简单的词法分析器。我对lexing感觉非常好,但现在我想改变我的输出。
#lang racket
(require parser-tools/lex)
(require (prefix-in : parser-tools/lex-sre))
(define in (open-input-string "MsRtcOAuth href=\"https://foo.com/WebTicket/oauthtoken\",grant_type=\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\", Bearer trusted_issuers=\"\", client_id=\"00000004-0000-0ff1-ce00-000000000000\""))
(define key-lexer
(lexer
;anything not an "="
[(:* (char-complement #\=))
;=>
(cons `(KEY, lexeme)
(equals-lexer input-port))]
;eof
[(eof) '()]))
(define equals-lexer
(lexer
[#\=
;=>
(value-lexer input-port)]
;eof
[(eof) '()]))
(define value-lexer
(lexer
;values are anything between two " "
[(concatenation #\" (:* (char-complement #\")) #\")
;=>
(cons `(VAL, lexeme)
(comma-lexer input-port))]
;eof
[(eof) '()]))
(define comma-lexer
(lexer
[(concatenation (:* whitespace) #\, (:* whitespace))
;=>
(key-lexer input-port)]
;eof
[(eof) '()]))
(key-lexer in)
现在,输出如下:
'((KEY "MsRtcOAuth href")
(VAL "\"https://foo.com/WebTicket/oauthtoken\"")
(KEY "grant_type")
(VAL "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"")
(KEY "Bearer trusted_issuers")
(VAL "\"\"")
(KEY "client_id")
(VAL "\"00000004-0000-0ff1-ce00-000000000000\""))
我更喜欢的是对的列表,类似于:
(("MsRtcOAuth href" . "\"https://foo.com/WebTicket/oauthtoken\"")
("grant_type" . "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"") etc...
任何帮助或指示非常感谢。谢谢!
答案 0 :(得分:1)
这是将你所拥有的东西转化为你想要的东西的一种方法:
(define (prettify key-val-pairs)
(match key-val-pairs
[(list (list 'KEY key) (list 'VAL val) more ...)
(cons (list key val)
(prettify more))]
[_ key-val-pairs]))
(prettify
'((KEY "MsRtcOAuth href")
(VAL "\"https://foo.com/WebTicket/oauthtoken\"")
(KEY "grant_type")
(VAL "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"")
(KEY "Bearer trusted_issuers")
(VAL "\"\"")
(KEY "client_id")
(VAL "\"00000004-0000-0ff1-ce00-000000000000\"")))
输出:
'(("MsRtcOAuth href" "\"https://foo.com/WebTicket/oauthtoken\"")
("grant_type" "\"urn:microsoft.rtc:windows,urn:microsoft.rtc:anonmeeting,password\"")
("Bearer trusted_issuers" "\"\"")
("client_id" "\"00000004-0000-0ff1-ce00-000000000000\""))