Is there any idiomatic way to replace strings whic...
# announcements
p
Is there any idiomatic way to replace strings which can contains parameters? For instance my string is :
Copy code
ANIMAL:TYPE:{variable1};NAME:{variable2};AGE:{variable3};FAMILY:{variable4};
Note, perhaps
variable4
is null/empty and I have anything there, I mean I should be able to replace with "" if it's not present
f
Kotlin provides
Regex.replace
that takes a lamda with which you can efficiently perform such replacements.
r
I don’t fully understand your example; do you mean this?
Copy code
val mightBeNull: String? = null
val interpolatedString = "A string with $mightBeNull"
where
interpolatedString
would resolve to
A string with null
, but you want
A string with
? If so I can offer two options. Small but ugly:
Copy code
val mightBeNull: String? = null
val interpolatedString = "A string with ${mightBeNull ?: ""}"
Or longer but more easy to read:
Copy code
val mightBeNull: String? = null
val notNull = mightBeNull ?: ""
val interpolatedString = "A string with $notNull"
Personally I prefer the second, I find logic inside `${}`in an interpolated string is hard for me to parse.
t
val params = mapOf(
"variable1" to "a",
"variable2" to "",
"variable3" to null,
// "variable4" not defined
)
val str = "ANIMAL:TYPE:{variable1};NAME:{variable2};AGE:{variable3};FAMILY:{variable4};"
val str2 = """\{(\w+)\}""".toRegex().replace( str){ params[it.groupValues[1]] ?: ""}
println(str2)
p
Sorry is hard to explain, I have a String as :
Copy code
ANIMAL:TYPE:{variable1};NAME:{variable2};AGE:{variable3};FAMILY:{variable4};
And I want to change only the variables1,2,3,4 with my data, so I wanted to know if there's an easy way to replace, I mean I know there's a replace function and I could create something like
ANIMATYPEVAR1;NAME:VAR2..
And then just replace this VAR1, VAR2, but I wanted to know more ways to do it.
f
Regex replace is your friend.
p
I see... ok thanks