我在字符串的末尾有一個字符串和一些模式。我怎樣才能在這個單詞的末尾完全刪除這個模式,但即使它存在於開始或中間,也沒有更多。例如,該字符串是clojure刪除字符串中模式的最後一個入口
PatternThenSomethingIsGoingOnHereAndLastPattern
,我需要刪除「模式」的結尾,這樣的結果將是
PatternThenSomethingIsGoingOnHereAndLast
我怎麼能這樣做?
我在字符串的末尾有一個字符串和一些模式。我怎樣才能在這個單詞的末尾完全刪除這個模式,但即使它存在於開始或中間,也沒有更多。例如,該字符串是clojure刪除字符串中模式的最後一個入口
PatternThenSomethingIsGoingOnHereAndLastPattern
,我需要刪除「模式」的結尾,這樣的結果將是
PatternThenSomethingIsGoingOnHereAndLast
我怎麼能這樣做?
您的問題沒有指定模式是否必須是正則表達式或純字符串。在後一種情況下,你可以只使用簡單的方法:
(defn remove-from-end [s end]
(if (.endsWith s end)
(.substring s 0 (- (count s)
(count end)))
s))
(remove-from-end "foo" "bar") => "foo"
(remove-from-end "foobarfoobar" "bar") => "foobarfoo"
對於一個正則表達式的變化,看到answer of Dominic Kexel。
您可以使用replaceAll
=>(.replaceAll 「PatternThenSomethingIsGoingOnHereAndLastPattern」 「花樣$」, 「」)
「PatternThenSomethingIsGoingOnHereAndLast」
=> (clojure.string /替換「PatternThenSomethingIsGoingOnHereAndLastPattern」#「Pattern $」「」)你需要在這裏 「PatternThenSomethingIsGoingOnHereAndLast」
我所做的一切相信
(def string "alphabet")
(def n 2)
(def m 4)
(def len (count string))
;starting from n characters in and of m length;
(println
(subs string n (+ n m))) ;phab
;starting from n characters in, up to the end of the string;
(println
(subs string n)) ;phabet
;whole string minus last character;
(println
(subs string 0 (dec len))) ;alphabe
;starting from a known character within the string and of m length;
(let [pos (.indexOf string (int \l))]
(println
(subs string pos (+ pos m)))) ;lpha
;starting from a known substring within the string and of m length.
(let [pos (.indexOf string "ph")]
(println
(subs string pos (+ pos m)))) ;phab
字符串處理是其中的Clojure使得大量使用底層平臺的區域。 '.endsWith'和'.replaceAll'方法都使用Java String類的方法。假設你在JVM上,那就是要走的路。如果你正在使用Clojurescript或者在CLR上,那麼你將會有一個不同的實現。 –