This example uses a relatively simple regular expression for URL validation. For more robust validation, you might consider a more comprehensive regex or a dedicated library. It's important to note that this function only checks for basic URL syntax. It doesn't verify that the URL actually exists or is accessible.
A simple Kotlin example to show if a string is a URL.
import java.util.regex.Pattern
fun isUrl(urlString: String): Boolean {
val urlPattern = Pattern.compile(
"^((https?|ftp|gopher|telnet|file|news|data)://)" +
"([a-zA-Z0-9-._~%!$&'()*+,;=:@/?#]+)+$"
)
return urlPattern.matcher(urlString).matches()
}
fun main() {
val validUrl = "https://www.example.com"
val invalidUrl = "This is not a URL"
println("Is '$validUrl' a URL? ${isUrl(validUrl)}") // Output: true
println("Is '$invalidUrl' a URL? ${isUrl(invalidUrl)}") // Output: false
}
Import java.util.regex.Pattern
: This imports the necessary class for working with regular expressions.
isUrl(urlString: String): Boolean
Function:
- Takes a
String
representing the potential URL. - Creates a
Pattern
object using a regular expression to match URLs. This regex checks for common URL patterns, including protocol, domain, and path. - Uses
matcher()
to create aMatcher
object for the input string. - Calls
matches()
to check if the input string matches the regular expression. - Returns
true
if the string is a valid URL,false
otherwise.
main()
Function:
- Defines two strings, one a valid URL and the other not.
- Calls
isUrl()
for each string and prints the results.