开发者

Getting arguments out of regexp

开发者 https://www.devze.com 2023-03-16 14:09 出处:网络
I want it to return 450 in some way, the $1 is just a silly variable name. It\'s like the reverse of format. What is 开发者_如何学运维the clojure regex magic for achieving this?

I want it to return 450 in some way, the $1 is just a silly variable name. It's like the reverse of format. What is 开发者_如何学运维the clojure regex magic for achieving this?

(re-something #"$1\sUSD" "450 USD")


user=> (re-find #"(\d\d\d) (USD)" "450 USD")
["450 USD" "450" "USD"]
user=> (nth *1 1)
"450"


I like to use re-find, if-let and destructuring. I very often write parsing code in the following pattern:

(def currency-regex #"(\d+) ([A-Z]{3})")

(defn parse-currency [s]
  (if-let [[_ amount currency] (re-find currency-regex s)]
    (process amount currency)
    (signal-error s)))


I find myself using this structure a lot to match my first group in a regex:

(second (re-find #"foo(bar)" "This is a foobar example"))
;=> "bar"

...because more often than not, I'm just capturing one item, like you are with the numerals. To make your code read better, you could alias the second function for this situation, so your intent is clear:

(def first-match second)
(first-match (re-find #"foo(bar)" "This is a foobar example"))
;=> "bar"

Maybe first-match could be first-group to be more precise, but you get the idea. Now the intent of picking out the second item from the return value of re-find is clearer.

0

精彩评论

暂无评论...
验证码 换一张
取 消