Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure remove last entrance of pattern in string

Tags:

string

clojure

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?

like image 903
Sergey Avatar asked Dec 01 '22 20:12

Sergey


1 Answers

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.

like image 139
Michiel Borkent Avatar answered Dec 19 '22 03:12

Michiel Borkent