テキストの検索と置換

Clojure:
テキストの検索と置換

How to: (方法)

; 文字列置換の基本例
(replace-first "cat" "bat" "the cat sat on the mat")
; 出力: "the bat sat on the mat"

; 正規表現を使った文字列置換
(replace-first #"cat" "bat" "the cat sat on the cat mat")
; 出力: "the bat sat on the cat mat"

; 全部の該当箇所を置換する
(clojure.string/replace "the cat sat on the cat mat" #"cat" "bat")
; 出力: "the bat sat on the bat mat"

Deep Dive (深いダイビング)

テキストの検索と置換はエディタやワードプロセッサが最初に導入した機能の一つです。Clojureではclojure.string/replace 関数などを使ってシンプルな置換ができます。正規表現の利用が可能で、複雑なパターンの検索や置換も対応しています。初期のプログラム言語ではテキスト処理が面倒だったが、Clojureのような現代言語はパワフルで柔軟な文字列操作機能を備えています。他にもテキストを処理する方法はありますが、clojure.stringライブラリは簡潔に書くことができるため最も普及しています。

See Also (参照)