Regular expressions (Regex) are an incredibly useful tool in searching/extracting text for matches within a specific search pattern.
Fields of application include form validation, trasnlating data, replacing strings, and many other uses.
This regex will match strings that contain relative file path or extension.
((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+)+\.[a-z]+$
- Anchors
- Quantifiers
- OR Operator
- Character Classes
- Grouping and Capturing
- Bracket Expressions
- Greedy and Lazy Match
The Anchor used in this regex expression $
indicates the end of a string.
The quantifiers used in this regex expression are ?
and +
.
?
is used in the sequence https?:
, indicating the string includes 0 or 1 's'.
+
is used at the end of the sequences ((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+)+
and a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+
indicating the string includes 1 or more of the previous expression
The OR Operator used in this expression is |
The OR operator indicates the string must include one of the following expressions:
\/
, \\
, /\/\
, https?:\\\\
, OR https?:\/\/
In order to be taken literally, the following characters were escaped using a \
:
/ as \/
\ as \\
[ as \[
] as /]
Parentheses create a captured group, the group can later be referenced.
Group 0 is the entire expression.
Group 1: ((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+)
- This group captures everything up until the file extension part of the string
Group 2: (\/|\\|\/\/|https?:\\\\|https?:\/\/)
- This group captures the path of the file extension.
Bracket expressions were used in the regex expression.
[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]
includes any letter or special character in the string before the .
[a-z]
- includes any letter in the string after the .
The quantifier +
was utilized and is a greedy operator. The +
operator will match as far as it possibly can within the text.
Feel free to follow or check out some of my other projects!
Copyright © 2021 Spires