Creating regular expression patterns

About this task

In this example, we are trying to create a regular expression pattern in JavaScript™ to look for the last value in the response, matching on the fourth match group.

Here is one implementation:


// the pattern used to extract the amount (found in match group 4 ($4)
var pattern = "COMP\\x3B(.*?)\\x3A(.*?)\\x3B(.*?)\\x3B(.*?)($|\\)"

// The weba.s.products hit attribute is the pattern found in the response. 
// We want the last one in the response.
// the amount is found in the fourth match group of the last match.
// var $amt = /$pattern/.exec
// ($P["APP.P__H_WEBA_S_PRODUCTS__HA__634261087410339197"].lastValue()).$4;



In the above example, two methods are called in a single line: .exec() and lastValue(). However, if the exec() method cannot find a match, it returns a null value, which generates a runtime error. Determining the source of this error is not straightforward.

To simplify debugging issues, Discover recommends breaking up the above JavaScript™ into multiple variable assignments, as in the following example:


//Define the regular expression
var pattern = "COMP\\x3B(.*?)\\x3A(.*?)\\x3B(.*?)\\x3B(.*?)($|\\)";

//Define the search buffer
var $search_buffer =
$P["APP.P__H_WEBA_S_PRODUCTS__HA__634261087410339197"].lastValue();

//Construct the RegEx object (If the pattern is invalid, this statement fails)
var $regex = new RegExp(pattern);

//Returns [FullMatch, Group1, Group2, Group3, Group4]
var $match = $regex.exec($search_buffer);

//Check to see if the match was successful and ensure that the match group is 
//available 
if($match && $match.length > 4) {
  var $amt = $match[4];
}



The above code separates the regular expression checks into simpler declarations, which isolate the regex definition, pattern definition, regex compilation, and regex execution. Using simpler declarations:

Procedure

  1. Simplifies automated and manual JavaScript™ validation
  2. Simplifies debugging issues

Results

The performance impacts of writing looser JavaScript™ are minimal.