简体   繁体   English

在 Clojure 或 Java 中使用正则表达式时,如何使用命名捕获组?

[英]When using regular expressions in Clojure or Java, how can I use named capture groups?

Since Java 7, named capture groups have been supported.自 Java 7 起,已支持命名捕获组。 However, the built-in Clojure functions re-matches , re-find , and re-groups do not allow access to the capture groups by name.但是,内置 Clojure 函数re-matchesre-findre-groups不允许按名称访问捕获组。

(ns tst.demo.core
  (:use tupelo.core tupelo.test))

(dotest
  ; Define a phone number pattern with some named capture groups.
  ; The reader literal #"..." allows us to avoid double-backslash like
  ; we'd need if using the form `(re-pattern <string>)`
  (let [patt #"(?<area>\d{3})-(?<prefix>\d{3})-(?<tail>\d{4})"]
    (is= java.util.regex.Pattern (type patt))

    ; `re-matches` will find the capture groups and stick them in a vector
    ; after the full match The capture groups are numbered starting with 1.
    ; The full match is like group zero.
    (is= ["619-239-5464" "619" "239" "5464"] (re-matches patt "619-239-5464"))

    ; Construct a java.util.regex.Matcher.  Keep in mind that it is a mutable object!
    (let [matcher (re-matcher patt "619-239-5464")]
      ; Execute the Matcher via `re-find`. It returns all 4 groups and caches them
      (is= ["619-239-5464" "619" "239" "5464"] (re-find matcher))

      ; `re-groups` simply returns the cached result from the Matcher
      (is= ["619-239-5464" "619" "239" "5464"] (re-groups matcher))

How can I use named capture groups in a regex from Clojure?如何在 Clojure 的正则表达式中使用命名捕获组?

The class java.util.regex.Matcher supports named capture groups, but you need to use Java interop to get at them. class java.util.regex.Matcher支持命名捕获组,但您需要使用 Java 互操作来获取它们。 An example:一个例子:

; We need the instance function Matcher.group( <name> ) to extract named groups
(is= "619" (.group matcher "area"))
(is= "239" (.group matcher "prefix"))
(is= "5464" (.group matcher "tail"))))

The above code is based on this template project .上面的代码就是基于这个模板项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM