Reputation: 11918
I have a string and some pattern at the end of the string. How can I remove this pattern exactly at the end of the word but nothing more even if it exists in the beginning or in the middle. For example, the string is
PatternThenSomethingIsGoingOnHereAndLastPattern
and I need to remove the "Pattern" at the end so that result would be
PatternThenSomethingIsGoingOnHereAndLast
How can I do that?
Upvotes: 5
Views: 5184
Reputation: 101122
You can use replaceAll
=> (.replaceAll "PatternThenSomethingIsGoingOnHereAndLastPattern" "Pattern$" "")
"PatternThenSomethingIsGoingOnHereAndLast"
=> (clojure.string/replace "PatternThenSomethingIsGoingOnHereAndLastPattern" #"Pattern$" "") "PatternThenSomethingIsGoingOnHereAndLast"
Upvotes: 8
Reputation: 2642
Everything you need here I do believe
(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
Upvotes: 0
Reputation: 34840
Your question doesn't specify if the pattern has to be a regex or a plain string. In the latter case you could just use the straightforward approach:
(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"
For a regex variation, see the answer of Dominic Kexel.
Upvotes: 10