Pablo
11/01/2020, 8:53 AMANIMAL: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 presentFleshgrinder
11/01/2020, 10:03 AMRegex.replace
that takes a lamda with which you can efficiently perform such replacements.Rob Elliot
11/01/2020, 11:55 AMval 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:
val mightBeNull: String? = null
val interpolatedString = "A string with ${mightBeNull ?: ""}"
Or longer but more easy to read:
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.tateisu
11/01/2020, 2:06 PMval 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)
Pablo
11/02/2020, 11:08 AMANIMAL: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.
Fleshgrinder
11/02/2020, 11:27 AMPablo
11/02/2020, 12:37 PM