为什么重新找到返回两个元素的向量?(why is re

编程入门 行业动态 更新时间:2024-10-23 22:37:40
为什么重新找到返回两个元素的向量?(why is re-find returning a vector with two elements?)

以这种方式使用重新查找时:

(re-find #"(\d{3})" "abc1245")

我得到:

["124" "124"]

当我期望只有一个价值。 这是怎么回事?

When using re-find in this way:

(re-find #"(\d{3})" "abc1245")

I get:

["124" "124"]

when I expect just one value. What's going on?

最满意答案

这是因为括号创建了一个正则表达式“组”。 看到

https://clojuredocs.org/clojure.core/re-find

举些例子。 以下是区别:

(re-find #"(\d{3})" "abc1245") => ["124" "124"] ; #1 (re-find #"\d{3}" "abc1245") => "124" ; #2 (re-seq #"\d{3}" "abc1245") => ("124") ; #3 (re-seq #"\d{3}" "abc12345678") => ("123" "456") ; #4

所以,#1给你的结果和“组结果”。 #2只给你匹配的子字符串。

#3为您提供了所有匹配的序列。 由于只有4位数字,所以剩余“5”不足以匹配3位数字。

#4总共有8位数字,所以我们得到"123"和"456"作为匹配,剩余7和8,因为我们只需要三位数字。

It is because the parentheses create a regex "group". See

https://clojuredocs.org/clojure.core/re-find

for examples. Here's the difference:

(re-find #"(\d{3})" "abc1245") => ["124" "124"] ; #1 (re-find #"\d{3}" "abc1245") => "124" ; #2 (re-seq #"\d{3}" "abc1245") => ("124") ; #3 (re-seq #"\d{3}" "abc12345678") => ("123" "456") ; #4

So, #1 gives you both the result and the "group result". #2 gives you just the matched substring.

#3 gives you a sequence of all matches. Since there are only 4 digits, the remaing "5" isn't enough to match 3 digits.

#4 gives 8 digits total, so we get "123" and "456" as matches, with 7 & 8 leftover since we only want triples of digits.

更多推荐

本文发布于:2023-07-06 07:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   元素   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!