Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax highlighting for regular expressions in Vim

Whenever I look at regular expressions of any complexity, my eyes start to water. Is there any existing solution for giving different colors to the different kinds of symbols in a regex expression?

Ideally I'd like different highlighting for literal characters, escape sequences, class codes, anchors, modifiers, lookaheads, etc. Obviously the syntax changes slightly across languages, but that is a wrinkle to be dealt with later.

Bonus points if this can somehow coexist with the syntax highlighting Vim does for whatever language is using the regex.

Does this exist somewhere, or should I be out there making it?

like image 294
Ben Gartner Avatar asked Jun 21 '10 22:06

Ben Gartner


2 Answers

Regular expressions might not be syntax-highlighted, but you can look into making them more readable by other means.

Some languages allow you to break regular expressions across multiple lines (perl, C#, Javascript). Once you do this, you can format it so it's more readable to ordinary eyes. Here's an example of what I mean.

You can also use the advanced (?x) syntax explained here in some languages. Here's an example:

(?x:          # Find word-looking things without vowels, if they contain an "s"
   \b                       # word boundary
   [^b-df-hj-np-tv-z]*      # nonvowels only (zero or more)
   s                        # there must be an "s"
   [^b-df-hj-np-tv-z]*      # nonvowels only (zero or more)
   \b                       # word boundary
)

EDIT:

As Al pointed out, you can also use string concatenation if all else fails. Here's an example:

regex = ""          # Find word-looking things without vowels, if they contain an "s"
   + "\b"                       # word boundary
   + "[^b-df-hj-np-tv-z]*"      # nonvowels only (zero or more)
   + "s"                        # there must be an "s"
   + "[^b-df-hj-np-tv-z]*"      # nonvowels only (zero or more)
   + "\b";                      # word boundary
like image 143
Kimball Robinson Avatar answered Sep 24 '22 23:09

Kimball Robinson


This Vim plugin claims to do syntax higlighting:

http://www.vim.org/scripts/script.php?script_id=1091

I don't think it's exactly what you want, but I guess it's adaptable for your own use.

like image 35
Peter Boughton Avatar answered Sep 21 '22 23:09

Peter Boughton