Examples of common or useful regular expressions I've created over the years.
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.
^(?:\((?=.*\))|{(?=.*}))?[a-fA-F0-9]{8}(?:-(?=(?:.*-){3}))?(?:[a-fA-F0-9]{4}-?){3}[a-fA-F0-9]{12}(?:\)(?<=\(.*)|}(?<={.*))?$
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.
As above without leading ^ and trailing $.
[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)}])
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.
https?:\/\/(?:www.)?(?:(?:youtube.com\/(?:v\/|embed\/|watch\?v=|\&v=))|(?:youtu.be\/))([^#\&\?\s]+)\S*
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.
https?:\/\/(?:(?:www\.)|(?:player\.))?(?:vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:\w+\/)?videos\/|album\/(?:\d+\/)?video\/|video\/|external\/)?(\d+))\S*
With thanks to Mike Masey for the starting point of this one.