文字列と文字列の最後にいくつかのパターンがあります。このパターンを単語の最後で正確に削除するにはどうすればよいですか。ただし、最初または途中に存在する場合でも、それ以上は削除できません。たとえば、文字列は
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"
正規表現のバリエーションについては、DominicKexelの回答を参照してください。
使用できます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