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
Finally I've found a way and it is actually easy:
This will return NULL if there is no regex chars in the string or, the subString before those chars
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.The above single line call to
replace
would leave unchaged any string not having any&
or#
in it. If desired, you could still use theif
check:Using RegEx:
If the result contains neither ‘&’ nor ‘#’ and you want the whole string to be returned:
If the result contains neither ‘&’ nor ‘#’ and you want null to be returned:
Not using RegEx:
If the result contains neither ‘&’ nor ‘#’ and you want the whole string to be returned:
If the result contains neither ‘&’ nor ‘#’ and you want null to be returned: