我怎么在clojure中这样做
"text".gsub(/(\d)([ap]m|oclock)\b/, '\1 \2')
Run Code Online (Sandbox Code Playgroud)
Mic*_*zyk 25
为了增加Isaac的答案,这就是你clojure.string/replace在这个特殊场合的用法:
user> (str/replace "9oclock"
#"(\d)([ap]m|oclock)\b"
(fn [[_ a b]] (str a " " b)))
; ^- note the destructuring of the match result
;^- using an fn to produce the replacement
"9 oclock"
Run Code Online (Sandbox Code Playgroud)
要添加到sepp2k的答案,这是你在使用"$1 $2"噱头时可以利用Clojure的正则表达式文字的方法(fn在这种情况下可以说比单独的更简单):
user> (.replaceAll (re-matcher #"(\d)([ap]m|oclock)\b" "9oclock")
; ^- note the regex literal
"$1 $2")
"9 oclock"
Run Code Online (Sandbox Code Playgroud)
那将replace在clojure.string命名空间中.你可以在这里找到它.
像这样使用它:
(ns rep
(:use [clojure.string :only (replace)]))
(replace "this is a testing string testing testing one two three" ;; string
"testing" ;; match
"Mort") ;; replacement
Run Code Online (Sandbox Code Playgroud)
replace 很棒,因为匹配和替换也可以是字符串/字符串或char/char,或者你甚至可以做匹配或字符串的正则表达式模式/函数.
您可以使用Java的replaceAll方法.电话会是这样的:
(.replaceAll "text" "(\\d)([ap]m|oclock)\\b" "$1 $2")
Run Code Online (Sandbox Code Playgroud)
请注意,这将返回一个新字符串(如gsubruby中的(没有爆炸)).gsub!在Clojure中没有等效的,因为Java/Clojure字符串是不可变的.
| 归档时间: |
|
| 查看次数: |
2077 次 |
| 最近记录: |