← servoy magazine

[Tip] Elegant RegExp.exec() example

  • Tips

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:

 

[image unavailable: Picture 17]

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

var fileData = plugins.file.readTXTFile( result )
if (fileData) { 
	
	// find and store editable regions			                        		
	var regexp = /pageData\.get\(\"([A-Z0-9 _]*)\"/gi   // match: <%=pageData.get("Sidebar")%>, any combination of letters, numbers, spaces and undersores
	var occurrence = null;
	var editables = []
	while (occurrence = regexp.exec( fileData )){	
		editables.push(occurrence[1])
	}

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

[image unavailable: 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.

Comments (2)

Tom Parry
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
David Workman
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.