Regex 球拍模式匹配不进行贪婪匹配
Racket语言中的模式匹配有Regex 球拍模式匹配不进行贪婪匹配,regex,pattern-matching,racket,Regex,Pattern Matching,Racket,Racket语言中的模式匹配有…来进行贪婪匹配(匹配0或更多),如果我想匹配如下内容,该怎么办: #lang racket (define (Modifier? t) (equal? t "Modifier")) (define (SimpleName? t) (equal? t "SimpleName")) (define (SimpleType? t) (equal? t "SimpleType")) (define (FieldDeclaration? t) (equal?
…
来进行贪婪匹配(匹配0或更多),如果我想匹配如下内容,该怎么办:
#lang racket
(define (Modifier? t) (equal? t "Modifier"))
(define (SimpleName? t) (equal? t "SimpleName"))
(define (SimpleType? t) (equal? t "SimpleType"))
(define (FieldDeclaration? t) (equal? t "FieldDeclaration"))
(match (match '("FieldDeclaration" ("Modifier") ("Modifier") ("SimpleType") ("VariableDeclarationFragment" ("SimpleName") ("StringLiteral")))
[(list (? FieldDeclaration? id) (? Modifier? m) ... (? SimpleType? t) (list _ (? SimpleName? n)) _ ...)
'yes]
[else 'no] )
其中打印的是“否”,而我希望打印的是“是”。我猜这是由。
(只需在链接页面中搜索“贪婪”),但我不太确定这一点…)
列表中可以有0到3个(“修饰符”)
s,因此如何匹配此表单?(实际上,函数XXX?
中有更多的事情要做,因此我必须使用表单(?XXX?x)
)
PS:有没有可能这样我就可以使用
n_m
这意味着匹配n到m次,就像正则表达式中的{n,m}
一样?事实上,不是贪婪的,你很快就拥有了它
工作两个问题:
首先,你的三个谓词是错误的。因为你的输入是
e、 g.(“修饰符”)
不是“修饰符”
,您想
匹配(列出“修饰符”)
而不是“修饰符”
这个谓词是OK的:
(define (FieldDeclaration? t)
(equal? t "FieldDeclaration"))
第二,我认为你在本书的最后部分有一个错误的结尾
您的模板--它应该是(列表(?SimpleName?n)……
不(列表(?SimpleName?n))\u……
这是完整的匹配表达式,我加了一些换行符使其匹配
我更容易理解:
(match '("FieldDeclaration"
("Modifier") ("Modifier")
("SimpleType")
("VariableDeclarationFragment" ("SimpleName") ("StringLiteral")))
[(list (? FieldDeclaration? id)
(? Modifier? m) ...
(? SimpleType? t)
(list _ (? SimpleName? n) _ ...))
'yes]
[_ 'no])
这会打印出“是的”
格雷格写道,“实际上……并不贪婪”,但。。。如以下示例所示:
racket@match.rkt> (match '(1 2 7 3 4 5 3 6 7 3 8) [(list a ... 3 b ...) (list a b)])
'((1 2 7 3 4 5 3 6 7) (8))
(match '(1 2 7 3 4 5 3 6 7 3 8) [(list (? number? a) ... 3 b ...) (list a b)])
'((1 2 7 3 4 5 3 6 7) (8))
我原以为会看到“((1 2 7)(4 5 3 6 7 3 8))。我在匹配我想要的前缀时遇到了问题,但是我得到了贪婪的行为
racket@match.rkt> (match '(1 2 7 3 4 5 3 6 7 3 8) [(list a ... 3 b ...) (list a b)])
'((1 2 7 3 4 5 3 6 7) (8))
(match '(1 2 7 3 4 5 3 6 7 3 8) [(list (? number? a) ... 3 b ...) (list a b)])
'((1 2 7 3 4 5 3 6 7) (8))