本文介绍了Racket中括号内容的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 Racket 中括号的内容?内容可能有更多的括号.我试过了:

How can I get contents of parenthesis in Racket? Contents may have more parenthesis. I tried:

(regexp-match #rx"((.*))" "(check)")

但是输出有(check)"三个而不是一个:

But the output has "(check)" three times rather than one:

'("(check)" "(check)" "(check)")

我只想要检查"而不是(检查)".

And I want only "check" and not "(check)".

对于嵌套括号,应返回内部块.因此 (a (1 2) c) 应该返回a (1 2) c".

for nested parenthesis, the inner block should be returned. Hence (a (1 2) c) should return "a (1 2) c".

推荐答案

括号捕获而不匹配.. 所以 #rx"((.*))" 对所有内容进行两次捕获.因此:

Parentheses are capturing and not matching.. so #rx"((.*))" makes two captures of everything. Thus:

(regexp-match #rx"((.*))" "any text")
; ==> ("any text" "any text" "any text")

结果列表将第一个作为整个匹配项,然后是第一组 acpturnig 括号,然后是这些括号内的那些作为第二个......如果你想匹配括号,你需要对它们进行转义:

The resulting list has the first as the whole match, then the first set of acpturnig paren and then the ones inside those as second.. If you want to match parentheses you need to escape them:

(regexp-match #rx"\\((.*)\\)" "any text")
; ==> #f
(regexp-match #rx"\\((.*)\\)" "(a (1 2) c)")
; ==> ("(a (1 2) c)" "a (1 2) c")

现在您看到第一个元素是整个匹配项,因为匹配项可能从搜索字符串中的任何位置开始,并在匹配项最大的位置结束.第二个元素是唯一的一个捕获.

Now you see that the first element is the whole match, since the match might start at any location in the search string and end where the match is largest. The second element is the only one capture.

如果字符串有额外的括号,这将失败.例如.

This will fail if the string has additional sets of parentheses. eg.

(regexp-match #rx"\\((.*)\\)" "(1 2 3) (a (1 2) c)")
; ==> ("(1 2 3) (a (1 2) c)" "1 2 3) (a (1 2) c")

这是因为表达式不知道嵌套.要意识到这一点,您需要像 Perl 中那些具有 (?R) 语法和朋友的递归正则表达式,但是球拍没有这个(还???)

It's because the expression isn't nesting aware. To be aware of it you need recursive reguler expression like those in Perl with (?R) syntax and friends, but racket doesn't have this (yet???)

这篇关于Racket中括号内容的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:14