Regex Syntax – Frequently Used

,

The following is common Regex Syntax that frequently is used when Writing a Redirect.

  • ^ – Match only if the following is at the beginning of the line
  • $ – Match only if the previous is at the end of the line
  • ? – Match the previous 0 or 1 times (makes it optional)
  • . – Match any single character
  • * – Match the previous 0 or more times
  • + – Match the previous 1 or more times
  • (x) – Matches x and remembers the match to be called using $1
  • (?:x) – Matches x but does not remember the match
  • x(?=y) – Matches x only if it is followed by y
  • x(?!y) – Matches x only if it is NOT followed by y
  • x|y – Matches x or y
  • [xyz] – Matches any character enclosed in the brackets. Note: This matches X, or Y, or Z; it doesn’t match the string “xyz”.
  • [^xyz] – Matches any character except for those listed in the brackets.
  • \ – “Escape” special characters. Thus \? literally matches ? not the syntax rule of “previous is option”.
  • \d \w \s – Matches and should be any Digit (number), Alphabetic Character (letter) or White Space (space bar) respectively.
  • \D \W \S – Matches everything But a Digit, Character, or White Space respectively.

Examples

Redirecting SSL Paths

In order to configure your site to use SSL correctly, you will need to configure URL paths using regex.  Below are some examples of how to construct regex rules for different file and path types:

Purpose

Example formatting

Include an entire directory but nothing beneath it

http://www.yourdomain.com/shop/

^/shop/?$

Include all subdirectories

http://www.yourdomain.com/shop/*

^/shop/.*

Include a single file

http://www.yourdomain.com/shop.php

^/shop\.php

Include any file of a specific type

^/shop/.*\.php – any php file

Include everything that contains a specific phrase

http://www.yourdomain.com/*shop*

^/.*shop

Non-SSL URL Redirects.

NOTE

  • “(.+)” and “(.*)” is matching “.” Any Character, “*” 0 or more times, or “+” 1 or more times, and Remembering the match. This is the most effective “Wild Card” Solution in Regex.
  • You can match “.*” and “.+” with out Remembering the match as well.
  • We are calling the matched content in the Source Input “(.+)” and adding it to the Destination via “$1”
  • If you were matching different parts of a URL, say “^/thisiswhere/(.+)/fileswere/(.+)” Then you could call each match separately using “$1” and “$2” respectively

Submit a Comment

Your email address will not be published. Required fields are marked *