Clojure-regular-expressions-replacefirst

提供:Dev Guides
移動先:案内検索

Clojure-正規表現の置き換え優先

交換優先

replace関数は、文字列内の部分文字列を新しい文字列値で置き換えるために使用されますが、最初に出現するのは部分文字列のみです。 部分文字列の検索は、パターンを使用して行われます。

構文

構文は次のとおりです。

(replace-first str pat replacestr)

パラメータ-「pat」は正規表現パターンです。 「str」は、パターンに基づいてテキストを検索する必要がある文字列です。 「replacestr」は、パターンに基づいて元の文字列で置き換える必要がある文字列です。

戻り値-部分文字列の置換が正規表現パターンを介して行われますが、最初に出現した新しい文字列。

Clojureのreplace-firstの例を次に示します。

(ns clojure.examples.example
   (:gen-class))

;; This program displays Hello World
(defn Example []
   (def pat (re-pattern "\\d+"))
   (def newstr1 (clojure.string/replace "abc123de123" pat "789"))
   (def newstr2 (clojure.string/replace-first "abc123de123" pat "789"))
   (println newstr1)
   (println newstr2))
(Example)

上記の例は、replace関数とreplace-first関数の違いを示しています。

出力

上記のプログラムは、次の出力を生成します。

abc789de789
abc789de123