Reputation: 82
I have a string like this val str = "luckycore.util.BigNum("0")"
, the first five character of the string e.g lucky
are dynamic and can change while rest of the string is fixed, what I was trying was to get output as
luckyInt(0)
i.e replace all charaters except dynamic one with Int
and also remove quotes around 0
, I tried using replace
and substring
methods and its working fine for me, but I want to get this output using regex
, I tried but nothing is working, someone please help.
one more case is:
input string = richardcore.util.BigNum("0")
output string = richardInt(0)
Upvotes: 1
Views: 112
Reputation: 2424
There is no need for Regex, you can simply do it:
val str = """luckycore.util.BigNum("0")"""
val l = str.replace(str.substring(str.indexOf("core"),str.indexOf("(")).trim,"Int").replace("\"","")
Upvotes: 1
Reputation: 22439
If I understand your requirement correctly, there is no need for Regex. You can define a simple function (in Scala) as follows:
// Replace substring trailing after the first n characters
def replaceTail(s: String, n: Int, tail: String) = {
s.substring(0, n) + tail
}
val str1 = """luckycore.util.BigNum("0")"""
replaceTail(str1, 5, "Int(0)")
res1: String = luckyInt(0)
val str2 = """richardcore.util.BigNum("0")"""
replaceTail(str2, 7, "Int(0)")
res2: String = richardInt(0)
Upvotes: 0
Reputation: 9878
You can try using the Regex ([a-z]{5})(core\.util\.BigNum\(\"0\"\))
and then replace the String with the first captured Group.
You can play with this regex at https://regex101.com/r/1DhgLo/1
I am not familiar with Scala or Java. But the Regex should be pretty much remain the same.
Upvotes: 1