Returns the groups from the most recent match/find. If there are no nested groups, returns a string of the entire match. If there are nested groups, returns a vector of the groups, the first element being the entire match.
user=> (def phone-number "672-345-456-3212") #'user/phone-number user=> (def matcher (re-matcher #"((\d+)-(\d+))" phone-number)) #'user/matcher user=> (re-find matcher) ["672-345" "672-345" "672" "345"] ;; re-groups gets the most recent find or matches user=> (re-groups matcher) ["672-345" "672-345" "672" "345"] user=> (re-groups matcher) ["672-345" "672-345" "672" "345"] user=> (re-find matcher) ["456-3212" "456-3212" "456" "3212"] user=> (re-groups matcher) ["456-3212" "456-3212" "456" "3212"] user=> (re-groups matcher) ["456-3212" "456-3212" "456" "3212"] user=> (re-find matcher) nil user=> (re-groups matcher) IllegalStateException No match found java.util.regex.Matcher.group (Matcher.java:468)
;;given a string to match user=> (def flight "AF-22-CDG-JFK-2017-09-08") #'User/flight ;; groups and give a name to matches user=> (def flight-regex #"(?<airlineCode>[A-Z0-9]+)-(?<flightNumber>[0-9]+[A-Z]?)-(?<from>[A-Z]+)-(?<to>[A-Z]+)-(?<year>[0-9]+)-(?<month>[0-9]+)-(?<day>[0-9]+)") #'user/flight-regex user=> (def matcher (re-matcher flight-regex flight)) #'user/matcher ;; it allows good grasp of meaning and understanding of the data extraction from the regex user=> (if (.matches matcher) {:airline-code (.group matcher "airlineCode") :flight-number (.group matcher "flightNumber") :from (.group matcher "from") :to (.group matcher "to") :year (.group matcher "year") :month (.group matcher "month") :day (.group matcher "day")} (throw (ex-info (str "Can't extract detailed value from flight")))) {:airline-code "AF", :flight-number "22", :from "CDG", :to "JFK", :year "2017", :month "09", :day "08"} user=> ;;Beware that groups are available in Java Regex not in Javascript ones...
; ; Java supports named capture groups ; ; Define a phone number pattern with some named groups (let [patt (re-pattern "(?<area>\\d{3})-(?<prefix>\\d{3})-(?<tail>\\d{4})")] ; `re-matches` will find the capturing 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)) ; We need the instance function Matcher.group( <name> ) to ; extract the named group (is= "619" (.group matcher "area")) (is= "239" (.group matcher "prefix")) (is= "5464" (.group matcher "tail"))))
re-groups