skip to Main Content

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("#")
}

3

Answers


  1. Chosen as BEST ANSWER

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

     val matchRegex = "[#&]".toRegex().find(myString)
     val manipulatedString = 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


  2. 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("[&#].*"), "")
    }
    
    Login or Signup to reply.
  3. 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 }
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search