Reputation: 97
I am trying to strip the string {"$outer":{}, (starts from curly brace and end with comma) in my input but I could not do it.
My input is like below
{"$outer":{},"size":"10","query":{"$outer":{},"match":{"$outer":{},"_all":{"$outer":{},"query":"VALLE","operator":"and"}}}}
I tried the below ways but both did not help me.
First Approach:
val dropString = "\"$outer\":{},"
val payLoadTrim = payLoadLif.dropWhile(_ == dropString).reverse.dropWhile(_ == dropString).reverse
This one did not do anything. Here is the output:
{"$outer":{},"size":"10","query":{"$outer":{},"match":{"$outer":{},"_all":{"$outer":{},"query":"VALLE","operator":"and"}}}}
Second Approach:
def stripAll(s: String, bad: String): String = {
@scala.annotation.tailrec def start(n: Int): String =
if (n == s.length) ""
else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length)
else start(1 + n)
@scala.annotation.tailrec def end(a: Int, n: Int): String =
if (n <= a) s.substring(a, n)
else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n)
else end(a, n - 1)
start(0)
}
Output from Second:
size":"10","query":{"$outer":{},"match":{"$outer":{},"_all":{"$outer":{},"query":"VALLE","operator":"
and Desired Output:
{"size":"10","query":{"match":{"_all":{"query":"VALLE","operator":"and"}}}
Upvotes: 1
Views: 1106
Reputation: 6460
When you need to cut off an exact prefix/suffix you can use .stripPrefix
/.stripSuffix
methods:
@ "abcdef".stripPrefix("abc")
res: String = "def"
@ "abcdef".stripSuffix("def")
res: String = "abc"
Note that if the string doesn't have such prefix (or suffix), it will stay unchanged:
@ "abcdef".stripPrefix("foo")
res: String = "abcdef"
@ "abcdef".stripSuffix("buh")
res: String = "abcdef"
Sometimes it's important to cut off from the beginning (or end), so if when you use .replace
, you should be careful and add ^...
(or ...$
) to the regex pattern, otherwise it may find a match somewhere in the middle and replace it.
Bonus: if you just want to check that a string has a given prefix/suffix, you can use .startsWith
/.endsWith
methods (plus .startsWith
can also take an offset).
Upvotes: 0
Reputation: 61666
You might want to use replace
:
val input = """{"$outer":{},"size":"10","query":{"$outer":{},"match":{"$outer":{},"_all":{"$outer":{},"query":"VALLE","operator":"and"}}}}"""
input.replace("\"$outer\":{},", "")
which returns:
{"size":"10","query":{"match":{"_all":{"query":"VALLE","operator":"and"}}}}
Upvotes: 3