Home > Software design >  Regex in kotlin
Regex in kotlin

Time:06-19

I'm trying to use substringBefore() fun with two char ("#" and "&"). How can i use regex for both cahrs? I dont want to do this:

if (myString.contains("&")) {            
    myString.substringBefore("&")    
} else if (myString.contains("#"))
    myString.substringBefore("#")
}

CodePudding user response:

If I understand correctly, substringBefore() does not accept a regex parameter. However, replace() does, and we can formulate your problem as removing everything from the first & or # until the end of the string.

myString.replace(Regex("[&#].*"), "")

The above single line call to replace would leave unchaged any string not having any & or # in it. If desired, you could still use the if check:

if (myString.contains("&") || myString.contains("#")) {
    myString.replace(Regex("[&#].*"), "")
}

CodePudding user response:

Finally I've found a way and it is actually easy:

 val matchRegex = "[#&]".toRegex().find(myString)
 val manipulatedUrl = matchRegex?.range?.first?.let {
   myString.substring(0, it)
 }

This will return NULL if there is no regex chars in the string or, the subString before those chars

CodePudding user response:

Using RegEx:

If the result contains neither '&' nor '#' and you want the whole string to be returned:

val result = myString.split('&', '#').first()

If the result contains neither '&' nor '#' and you want null to be returned:

val result = myString.split('&', '#').let { if (it.size == 1) null else it.first() }

Not using RegEx:

If the result contains neither '&' nor '#' and you want the whole string to be returned:

val result = myString.takeWhile { it != '&' && it != '#' }

If the result contains neither '&' nor '#' and you want null to be returned:

val result = myString.takeWhile { it != '&' && it != '#' }
  .let { if (it == myString) null else it }
  
  • Related