- Pattern Breakdown:
^(https?:\\/\\/)?
: Matches the protocol (http://
or https://
).(([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,}))
: Matches domain names.localhost
: Matches localhost
.((\\d{1,3}\\.){3}\\d{1,3})
: Matches IPv4 addresses.(\\:\\d+)?
: Matches the port number.(\\/[-a-zA-Z0-9%_@.&+=~]<em>)</em>$
: Matches the path.
This regex pattern is basic and may not cover all edge cases. Creating a regex that matches all valid URLs while excluding invalid ones can be challenging.