clojure删除字符串中模式的最后一个入口

Ser*_*gey 2 string clojure

我在字符串的末尾有一个字符串和一些模式.如何在单词的末尾精确地删除此模式,但即使它存在于开头或中间,也不会更多.例如,字符串是

PatternThenSomethingIsGoingOnHereAndLastPattern
Run Code Online (Sandbox Code Playgroud)

我需要删除末尾的"模式",以便得到结果

PatternThenSomethingIsGoingOnHereAndLast
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Mic*_*ent 7

您的问题没有指定模式是必须是正则表达式还是纯字符串.在后一种情况下,您可以使用简单的方法:

(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"
Run Code Online (Sandbox Code Playgroud)

有关正则表达式的变化,请参阅Dominic Kexel答案.

  • 没有 Java `(defn remove-from-end [s end] (if (str/ends-with? s end) (subs s 0 (- (count s) (count end))) s))` (2认同)

slo*_*oth 7

您可以使用 replaceAll

=>(.replaceAll"PatternThenSomethingIsGoingOnHereAndLastPattern""Pattern $""")
"PatternThenSomethingIsGoingOnHereAndLast"

要么 clojure.string/replace

=>(clojure.string/replace"PatternThenSomethingIsGoingOnHereAndLastPattern"#"Pattern $""")"PatternThenSomethingIsGoingOnHereAndLast"