You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A regular expression, or regex, is a sequence of characters that defines a search pattern that can be used to validate user input. This tutorial breaks down a regex used for matching a URL.
Summary
The following regex can be used to validate a URL and has been broken down in this tutorial by its components (anchor, quantifies, grouping constructs, bracket expressions, character classes, and character escapes). Each section describes the symbol, a description, and where the code is found within the regex.
Regex Matching a URL:
`/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/`
Asserts the position at the end of the string (or before the end of the string's line terminator, if present).
`/?$/``
Quantifiers
Symbol
Description
Code in Regex
?
Matches the previous token between 0 and 1 times, as many times as possible, giving back as needed.
(https?:\/\/)? matches the characters https : // literally \/?$/ matches the character / literally
(*)
Matches the prevoius token between 0 and unlimited times, as many times as possible, giving back as needed.
([\/\w \.-]*)*
(+)
Matches the previous token between 1 and unlimited times, as many times as possible, giving back as needed.
([\da-z\.-]+)
{2,6}
Matches the previous token between 2 and 6 times, as many times as possible, giving back as needed.
([a-z\.]{2,6})
Grouping Constructs
Symbol
Description
Code in Regex
(?:...)
Matches everything enclosed.
(https?:\/\/)?
Bracket Expressions
Symbol
Description
Code in Regex
[a-z]
Matches a single character in the range between a and z.
[a-z\.] matches a single character in the range between a & z with a character. [\da-z\.-] matches a single character in the range between a & z, before one digit equivalent to [0-9] & the characters . & -
[ \/ \w \.-]
Matching a single character present in the list to the right:
\/ = matches the character / \w = matches any word character equivalent to [a-zA-Z0-9_] \. = matches the character . - = matches the character -
Character Classes
Symbol
Description
Code in Regex
\d
Matches a single character that is a digit.
([\da-z\.-]+)
\w
Matches any word character. Alphanumeric charatcer plus underscore.
[\/\w \.-]
Character Escapes
Symbol
Description
Code in Regex
\d
Matches a single character that is a digit.
([\da-z\.-]+)
\w
Matches any word character. Alphanumeric charatcer plus underscore.