clojure相当于ruby的gsub

Sur*_*rya 11 regex clojure

我怎么在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)

  • 实际上我会认为基于功能的解决方案更加"通用",代价是一定数量的额外击键.(想象一下用它的长度的字符串表示替换第一组:`"asdf"` - >`"4"`;不能用`$ 1`&Co.真的可行.另一方面,你可以用`$ 1'做任何事情.也可以使用函数来完成.)但是,没有关于更简单选项的论据可能更合适. (6认同)

Isa*_*aac 5

那将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,或者你甚至可以做匹配或字符串的正则表达式模式/函数.


sep*_*p2k 5

您可以使用Java的replaceAll方法.电话会是这样的:

(.replaceAll "text" "(\\d)([ap]m|oclock)\\b" "$1 $2")
Run Code Online (Sandbox Code Playgroud)

请注意,这将返回一个新字符串(如gsubruby中的(没有爆炸)).gsub!在Clojure中没有等效的,因为Java/Clojure字符串是不可变的.