https://kotlinlang.org logo
e

elect

03/11/2021, 7:23 AM
is there an easiest/shorter way to drop the
g
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?
r

rnett

03/11/2021, 7:25 AM
replace("-g", "-")
, and you can use regex instead of a literal if you have a more complex pattern
e

elect

03/11/2021, 7:26 AM
ah, so easy, thanks Ryan
n

nkiesel

03/11/2021, 9:01 AM
be careful: git allows tag names like "a-g", and there the
replace("-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)
e

elect

03/11/2021, 9:29 AM
I think the dash is what is exclusive there, commit ids do not contain that
n

nkiesel

03/11/2021, 8:24 PM
commit ids cannot contain dashes, but a tag name can contain dashes. and
replace
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".
e

elect

03/13/2021, 9:23 AM
yeah, replacing the last occurrence would be safer in that case
what does the last
$
mean here
Regex("-g([a-z0-9]+)$")
?
n

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 occurances
Perhaps there should be a `String.replaceLast`stdlib method, similar to
String.replaceFirst
. With
Copy code
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", "-")
e

elect

03/15/2021, 6:37 PM
Regex is a beast I can never stop learning..
thanks Norbert