Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Visual Studio syntax-highlight strings in the Regex constructor?

Hi fellow programmers and nerds!

When creating regular expressions Visual Studio, the IDE will highlight the string if it's preceded by a verbatim identifier (for example, @"Some string). This looks something like this:

A screenshot of the highlighting

(Notice the way the string is highlighted). Most of you will have seen this by now, I'm sure.

My problem: I am using a package acquired from NuGet which deals with regular expressions, and they have a function which takes in a regular expression string, however their function doesn't have the syntax highlighting.

the function without highlighting

As you can see, this just makes reading the Regex string just a pain. I mean, it's not all-too-important, but it would make a difference if we can just have that visually-helpful highlighting to reduce the time and effort one's brain uses trying to decipher the expression, especially in a case like mine where there will be quite a quantity of these expressions.

The question

So what I'm wanting to know is, is there a way to make a function highlight the string this way*, or is it just something that's hardwired into the IDE for the specific case of the Regex c-tor? Is there some sort of annotation which can be tacked onto the function to achieve this with minimal effort, or would it be necessary to use some sort of extension?

*I have wrapped the call to AddStyle() into one of my own functions anyway, and the string will be passed as a parameter, so if any modifications need to be made to achieve the syntax-highlight, they can be made to my function. Therefore the fact that the AddStyle() function is from an external library should be irrelevant.

If it's a lot of work then it's not worth my time, somebody else is welcome to develop an extension to solve this, but if there is a way...

Important distinction

Please bear in mind I am talking about Visual Studio, NOT Visual Studio Code.

Also, if there is a way to pull the original expression string from the Regex, I might do it that way, since performance isn't a huge concern here as this is a once-on-startup thing, however I would prefer not to do it that way. I don't actually need the Regex object.

like image 892
Logix Avatar asked Dec 05 '22 08:12

Logix


1 Answers

According to https://devblogs.microsoft.com/dotnet/visual-studio-2019-net-productivity/#regex-language-support and https://www.meziantou.net/visual-studio-tips-and-tricks-regex-editing.htm you can mark the string with a special comment to get syntax highlighting:

  // language=regex
  var str = @"[A-Z]\d+;

or

  MyMethod(/* language=regex */ @"[A-Z]\d+);

(the comment may contain more than just this language=regex part)

The first linked blog talks about a preview, but this feature is also present in the final product.

like image 99
Klaus Gütter Avatar answered May 28 '23 03:05

Klaus Gütter