我在字符串的末尾有一个字符串和一些模式。我如何才能在单词的末尾准确地删除此模式,但即使它存在于开头或中间,也仅此而已。例如,字符串是
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"
有关正则表达式的变体,请参阅Dominic Kexel 的答案。
您可以使用replaceAll
=> (.replaceAll "PatternThenSomethingIsGoingOnHereAndLastPattern" "Pattern$" "")
"PatternThenSomethingIsGoingOnHereAndLast"
=> (clojure.string/replace "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