Jhon Magdalena
Jhon Magdalena

Reputation: 23

Regular expression replacement at the end of string not working in Kotlin for Android

I am trying to write a few lines in Kotlin for Android to replace 0, 1 or multiple slashes at the end of an url with a single slash, but it is not working.

The code below:

val firstUrl = "http://my.url.com/"
val expectedResult = "http://my.url.com/" // <-- same URL

val result = firstUrl.replace(Regex("(/*)$"), "/")

// Expected result:
// > result == "http://my.url.com/"
// Got result:
// > result == "http://my.url.com//"

assert(result == expectedResult)

// Throws:
// > java.lang.AssertionError: Assertion failed
// >    ...
// >    ...

I have tested the same code in JavaScript (run with NodeJS) and it works.

Are there any errors in my regex?

I am using Kotlin 1.4.10:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.10"

Android version: 8.0.0

Model: Samsung Galaxy A5 2017

Upvotes: 2

Views: 1379

Answers (2)

Adam Millerchip
Adam Millerchip

Reputation: 23129

An alternative to using regular expressions is to use the URL class to parse the URL, and normalize it however you want. For example:

import java.net.URL

fun URL.withSlash() = "$protocol://$host/"

fun main() {
    println(URL("http://example.com").withSlash())
    println(URL("http://example.com/").withSlash())
    println(URL("http://example.com//").withSlash())
}

Output:

http://example.com/
http://example.com/
http://example.com/

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You can use replaceFirst and consider removing the capturing parentheses from the regex since you are not using the captured value:

val firstUrl = "http://my.url.com/"
val result = firstUrl.replaceFirst(Regex("/*$"), "/")
print(result)

See the Kotlin demo.

When using replaceFirst, /*$ will only match once at the end of the string, and only one / will be added each time you run the method.

Upvotes: 2

Related Questions