Active Scripting

Practical use of Active Scripting: Regular Expressions

Clarion has a very limited support of regular expressions. With javascript we can use the full power of regular expressions:

  • search for a match between a regular expression and a specified string
  • replace some or all matches
  • turn a string into an array of strings, by separating the string at each instance of a specified separator string

An example of replace feature:

var name1 = 'John Smith';
var re = /(\w+)\s(\w+)/;
var name2 = name1.replace(re, '$2, $1');  // expected result: 'Smith, John'

An example of split feature:

var s = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';
var re = /\s*(?:;|$)\s*/;
var arr = s.split(re);

I wrote a class that implements js regular expressions properties and methods:

  • Test - returns true if match found
  • Exec - returns an array of matches
  • Match - returns an array of matches
  • Search - returns the index of the first match
  • Replace - returns a new string with some or all matches of a pattern replaced by a replacement
  • ReplaceFunction - uses a function to be invoked to create the new substring
  • Split - returns an array of strings, split at each point where the separator occurs in the given string
  • LastIndex - the index at which to start the next match

so examples above can be written in Clarion like this:

  re.CreateNew('(\w+)\s(\w+)')
  name = re.Replace(s, '$2, $1')

and this

  re.CreateNew('\s*(?:;|$)\s*')
  len = re.Split(s)
  LOOP i = 1 TO len
    name = re.MatchedItem(i)
  END
1 Like