Regularly Expressed Regular Expressions

Examples of common or useful regular expressions I've created over the years.

, by Joe Glombek

Useful expressions

I'll keep coming back to this blog post as I create more, so it might be worth a bookmark!

The regular expressions that start with ^ (start of string/line) and end with $ (end of string/line) will ensure the whole string matches. This is useful for validating a string is in the format you expect. To find a string in the format you expect inside another string, these can be omitted.

Most of these regular expressions can be changed to the other method simply by adding/removing the ^(start of string/line) and $ (end of string/line) characters at the start and end respectively.

GUID

Validate a string is a GUID

^(?:\((?=.*\))|{(?=.*}))?[a-fA-F0-9]{8}(?:-(?=(?:.*-){3}))?(?:[a-fA-F0-9]{4}-?){3}[a-fA-F0-9]{12}(?:\)(?<=\(.*)|}(?<={.*))?$

Open in RegExr

Matches guids in most formats that .NET's Guid.Parse can handle (except 0x format), is case insensitive, dashes and brackets are optional, but brackets must match.

Replace a GUID inside a longer string

As above without leading ^ and trailing $.

Find inside a longer string

[a-fA-F0-9]{8}(?:-(?=(?:[a-fA-F0-9]+-[a-fA-F0-9]+){3}))?(?:[a-fA-F0-9]{4}-?){3}[a-fA-F0-9]{12}(?=[$\s)}])

Open in RegExr

This one is simpler as it doesn't need to worry about the brackets - we're looking for the bare minimum that constitutes a GUID.

YouTube URLs

https?:\/\/(?:www.)?(?:(?:youtube.com\/(?:v\/|embed\/|watch\?v=|\&v=))|(?:youtu.be\/))([^#\&\?\s]+)\S*

Open in RegExr

Will match many forms of YouTube URL (default, short links, embed). The first group in the match will be the video ID which can be used to construct an embed URL.

Vimeo URLs

https?:\/\/(?:(?:www\.)|(?:player\.))?(?:vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:\w+\/)?videos\/|album\/(?:\d+\/)?video\/|video\/|external\/)?(\d+))\S*

Open in RegExr

With thanks to Mike Masey for the starting point of this one.