This post is part of the series 'Visual Studio Tips and Tricks'. Be sure to check out the rest of the blog posts of the series!
- View and edit the Tab Order of Windows Forms Controls
- Comparing files using Visual Studio
- Visual Studio Tips and tricks: Clipboard history
- Visual Studio Tips and tricks: Open recently closed files
- Visual Studio Tips and tricks: Multi-line and multi-cursor editing
- Visual Studio Tips and tricks: Extend/Reduce selection
- Visual Studio Tips and tricks: Undock/Re-dock a tool window
- Visual Studio Tips and tricks: Regex editing (this post)
- Visual Studio Tips and tricks: Find the current opened file in the solution explorer
- Visual Studio Tips and tricks: Default startup project
- Visual Studio Tips and tricks: Open the documentation of a symbol
- Visual Studio Tips and tricks: Paste as JSON
- Visual Studio Tips and tricks: Add project reference using drag & drop
In C#, a regex is just a string. When the pattern is not simple, it can be hard to understand it. Visual Studio 2019 comes with some improvements to help you working with regexes.
#Regex are colorized
Each part of the pattern is colorized. It's easy to distinguish special characters, groups, quantifiers, comments, etc.:
The colorization depends on the regex options:
#Autocompletion works inside the pattern string
IntelliSense helps you to write the regex pattern. It helpful to discover the syntax or to autocomplete character categories:
#Matching parentheses are highlighted
To quickly find where the group starts or ends, Visual Studio highlight the matching parentheses:
#Backreferences are highlighted
When you see a backreference in the pattern, it is not easy to find the referenced group, especially for numbered backreferences. To quickly identify the referenced group, Visual Studio highlight it when your cursor is on a backreference:
#Errors in the pattern are reported
If the pattern is not valid, you'll get an error at runtime. What you want is to detect errors as soon as possible. Visual Studio reports errors in the pattern, so you can fix it:
#You can use a comment to colorize any string
Visual Studio automatically detects the string used in Regex methods (Regex constructor or static methods). But you may need to construct a string with the pattern before using it in a Regex method. You can instruct Visual Studio to consider any string as a regex pattern using a comment. You can also set the regex options in the comment.
The comment can be just before the string using
/* language=regex */ or on the preceding line using
// language=regex. Use a comma to add the regex options.
#Check your Visual Studio settings
If the above functionalities doesn't work, check your Visual Studio settings:
Do you have a question or a suggestion about this post? Contact me!