elect
03/11/2021, 7:23 AMg
in a string such as v0.1.9-1-g3a259e0
(which is always "$version-g$commitId") other than using something relying on lastIndexOf(-g)
and then combining the two substrings?rnett
03/11/2021, 7:25 AMreplace("-g", "-")
, and you can use regex instead of a literal if you have a more complex patternelect
03/11/2021, 7:26 AMnkiesel
03/11/2021, 9:01 AMreplace("-g", "-")
will not work correctly. Using `replace(Regex("-g([a-z0-9]+)$"), "-$1")`is a safer approach (assuming you are really dealing with git describe
output where the commit id is always a lowercase hex value)elect
03/11/2021, 9:29 AMnkiesel
03/11/2021, 8:24 PMreplace
replaces all and not just the last occurrence. Therefore, a tag name "a1-good" combined with commit id "abc123" will be combined to "a-good-gabc123" and "a-good-gabc123".replace("-g", "-")
will result in "a-ood-abc123" instead of the intended "a-good-abc123".elect
03/13/2021, 9:23 AM$
mean here Regex("-g([a-z0-9]+)$")
?nkiesel
03/15/2021, 6:14 PM$
matches "end of input". This guarantees that the part before it really is the commit id. Without the "$", you would get wrong results for a tag like "a-gdef" because `"a-gdef-gabc123".replace(Regex("-g([a-z0-9]+)"), "-$1")`will return "a-def-abc123" instead of the intended "a-gdef-abc123" because the regex matches twice and "replace" replaces all matching occurancesString.replaceFirst
. With
fun String.replaceLast(oldValue: String, newValue: String, ignoreCase: Boolean = false): String {
val index = lastIndexOf(oldValue, ignoreCase = ignoreCase)
return if (index < 0) this else this.replaceRange(index, index + oldValue.length, newValue)
}
you could just use "a-gdef-gabc123".replaceLast("-g", "-")
elect
03/15/2021, 6:37 PM