Regular Expression-Objects in vCO Scripts

Recently there was a great discussion on the forums about how to match Workflow input parameters against a Regular Expression: http://communities.vmware.com/message/2064306 (make sure to read through the complete thread to get Christophe’s (www.vcoteam.info) examples!)

Create RegExp Objects

Regular Expressions are used in JavaScript as objects of type ‘RegExp’. You can create them explicitly via constructor new RegExp() or directly with /pattern/modifiers-syntax:

//using the constructor
//new RegExp(pattern, modifiers);
var ipPattern= new RegExp("^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$");

//Or, to save a bit of typing, JavaScript provides a simpler syntax;
//var pattern = /pattern/modifiers;
var ipPattern= /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/;

(you might remember that from the E4X-syntax for XML-handling: http://www.vcoportal.de/2011/03/xml-handling-the-e4x-way/)

Use RegExp Objects

var ipPattern= /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/;
// as parameter for String-methods
var ip = "192.168.1.1";
var isValidIp = (ip.match(ipPattern) != null);
System.debug('Is the String ' + ip + ' a valid IP-address? ' + isValidIp);

ip = "192.168.1.678";
isValidIp = (ip.match(ipPattern) != null);
System.debug('Is the String ' + ip + ' a valid IP-address? ' + isValidIp);

//with the RegExp-object's own methods exec(), test()...
var validation = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/;
var creditCardNumber = "1234123412341234";
var isValidCreditCardNumber = validation.test(creditCardNumber); //returns a boolean
System.debug('isValidCreditCardNumber? :' + isValidCreditCardNumber);

(If you have a real world use case for the last example, let me know!  It’s on my todo-list next to an “How to integrate vCO with Paypal” article… :mrgreen:)

References

To feel the power of Regular Expressions (they even look very geeky  ;-)) visit:
http://www.w3schools.com/js/js_obj_regexp.asp
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
http://www.regular-expressions.info/examples.html

To become a Wizard, read following books (and :-)### grow a beard):
http://www.amazon.com/exec/obidos/ASIN/0596520689
http://www.amazon.com/exec/obidos/ASIN/0596528124/

And, as final pro-tips for the use of String.search(regexp):

  • It returns a number with the position of the first match (there is a mistake in the vCO API Explorer!), and
  • -1 is not false in JavaScript!!!