Skip to content

Instantly share code, notes, and snippets.

@imSpires
Last active October 6, 2021 21:35
Show Gist options
  • Save imSpires/974eb4ece6aaac018a19e8363bb5f7d6 to your computer and use it in GitHub Desktop.
Save imSpires/974eb4ece6aaac018a19e8363bb5f7d6 to your computer and use it in GitHub Desktop.
Regex Tutorial

Matching a Relative File Path or File Extension

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.

Summary

This regex will match strings that contain relative file path or extension.

((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9 _@\-^!#$%&+={}.\/\\\[\]]+)+\.[a-z]+$

Table of Contents

Regex Components

Anchors

The Anchor used in this regex expression $ indicates the end of a string.

Quantifiers

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

OR Operator

The OR Operator used in this expression is |

The OR operator indicates the string must include one of the following expressions:

\/, \\, /\/\, https?:\\\\, OR https?:\/\/

Character Classes

In order to be taken literally, the following characters were escaped using a \:

/ as \/

\ as \\

[ as \[

] as /]

Grouping and Capturing

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

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 .

Greedy and Lazy Match

The quantifier + was utilized and is a greedy operator. The + operator will match as far as it possibly can within the text.

Author

Feel free to follow or check out some of my other projects!

Copyright © 2021 Spires

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment