Code-Parsing Regular Expressions via Lighter.js

By  on  

Perfecting a regular expression can take a lot of time and testing but once achieved can be a absolutely golden. While looking through the source code of MooTools syntax highlighter Lighter.js I stumbled upon a few code-parsing regular expressions that you might be interested in.

The JavaScript

	// Matches a C style single-line comment.
	slashComments: /(?:^|[^\\])\/\/.*$/gm,
	
	// Matches a Perl style single-line comment.
	poundComments: /#.*$/gm,
	
	// Matches a C style multi-line comment.
	multiComments: /\/\*[\s\S]*?\*\//gm,
	
	// Matches a string enclosed by single quotes.
	aposStrings:   /'[^'\\]*(?:\\.[^'\\]*)*'/gm, 
	
	// Matches a string enclosed by double quotes.
	quotedStrings: /"[^"\\]*(?:\\.[^"\\]*)*"/gm, 
	
	// Matches both.
	strings:       /'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"/gm,
	
	// Matches a property: .property style.
	properties:    /\.([\w]+)\s*/gi,   
	
	// Matches a method call: .methodName() style.
	methodCalls:   /\.([\w]+)\s*\(/gm, 
	
	// Matches a function call: functionName() style.
	functionCalls: /\b([\w]+)\s*\(/gm,   
	
	// Matches any of the common brackets.
	brackets:      /\{|\}|\(|\)|\[|\]/g, 
	
	// Matches integers, decimals, hexadecimals.
	numbers:       /\b((?:(\d+)?\.)?[0-9]+|0x[0-9A-F]+)\b/gi 

Regular expressions can look heinous so I apologize to anyone whose brains imploded after looking at the above hieroglyphics text. Have useful regular expressions you use often? Share them!

Recent Features

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

Incredible Demos

Discussion

  1. David: very interesting, could you provide examples for each expression? ty so much!

  2. That’s pretty neat

    I’ve always used http://www.gskinner.com/RegExr/ to text my RegExp

  3. Well, im not a veteran programmer but i did a noobMatcher to test my regExp hehe

    http://vrs.host56.com/noobMatcher/

  4. Thanks for this Tutorial. Can u provide Demo for this.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!