Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex in kotlin

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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("[&#].*"), "")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading