Regex

Estimated reading time: 1 min

In Swift Performance you can apply Regex in different places, mostly to exclude URLs of parts from caching.

What is REGEX (Regular Expressions)?

A regular expression is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as *.txt to find all text files in a file manager. The regex equivalent is .*\.txt.

But you can do much more with regular expressions. In a text editor like EditPad Pro or a specialized text processing tool like PowerGREP, you could use the regular expression \b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,6}\b to search for an email address. Anyemail address, to be exact. A very similar regular expression can be used by a programmer to check if the user entered a properly formatted email address. In just one line of code, whether that code is written in Perl, PHP, Java, a .NET language or a multitude of other languages.

Since “regular expressions” is a mouthful, you will usually find the term abbreviated as “regex” or “regexp”. We prefer “regex”, since it can be easily pluralized as “regexes”.

Since PHP 7.3 you need to escape hyphen as well: #/product\-item(.*)/#

Here you can test if your Regex is valid.

example 1
exclude all multilingual contact pages, such as /contact – /contact-us – /contactos – /kontakt
regex
#/?.*onta?.*t\?.*#

example 2
For images
#/image(.*)/#

example 3
Exclude all pages/URLs which contain https://www.yourdomain.com/product-offers/../..
#/product\-offers(.*)/#

example 4
target all “/store/something” urls but NOT “/store/” itself
#/store\.+#

example 5
All pages, except homepage
#^/?$#

example 6
for date archives
#(\d{4})(/(\d{2}))?(/(\d{2}))?#

example 7
for tags
#/tag/(.*)/#

Note: It’s an advanced feature of Swift. We advice not to use Regex, when you don´t understand exactly what it is and how you can apply it. We suggest to use just parts, but you don’t need regex for this. Eg you can add an exception for “/contact” it will be true for all languages, same for products, you can just add “/product/”.
Was this article helpful?
Dislike 0 4 of 4 found this article helpful.