« [Tips] Automatically Create an Etherpad..."Pad" from Servoy | Main | [Tip] Creating records »

January 05, 2011

[Tip] Elegant RegExp.exec() example

I just figured out that the RegExp.exec() function cycles through all matches when used with the "g" flag on (because it starts searching from the end position from the last time it was run). Starting with:

 

Picture 17

The amount of code needed to return all editable area names in a Sutra CMS template file is reduced to:

Each iteration through changes the RegExp object which returns other useful info:

Picture 15

Waded through a bazillion google search results before this one tipped me off (google as a search engine is starting to piss me off—talk about SEO spam):

http://www.bennadel.com/blog/697-Javascript-Exec-Method-For-Regular-Expression-Matching.htm

Pretty sweet. After years, finally figured this regexp technique out. I'm almost to the point where I may never have to use a Utils.string..() function ever again. Yay, better late than never.

| Posted by David Workman on January 5, 2011 at 04:27 PM in Tips | Permalink

Comments

An alternative to defining the RegExp is this (not sure of the quotes but you get the idea):
var regexp = new RegExp('/pageData\.get\(\"([A-Z0-9 _]*)\"','gi' );

then you can do other operations such as test etc as well as do a regexp.exec(...)

Reference:
http://www.regular-expressions.info/javascript.html

Posted by: Tom Parry | May 13, 2011 8:48:59 PM

Have to escape out the backslashes using the literal string approach:

var regexp = new RegExp('pageData\\.get\\(\\"([A-Z0-9 _]*)\\"')

Not as readable but it allows you to build up regular expressions on the fly (allowing user input for example).

No difference in what functions you can run on the resulting regexp variable.

Posted by: David Workman | May 16, 2011 6:00:55 PM

Post a comment