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