Regular expressions
LScript now has in-language support for regular and search-and-replace expressions. Regular expressions are powerful pattern matching functions that have their own special meta- character langauge. This pattern-matching system originated on the UNIX operating system, and has permeated a great many places in the software world. There is a large body of reference available for regular expressions, so I will not provide a detailed explanation of them here. Rather, I will tell you how to employ them in LScript.
To perform pattern matching using regular expression in LScript, you need to use the new "s~~" operator. This operator instructs LScript to use the regular expression provided to compare against a character string to see if the pattern exists.
// see if the string begins with a
// capital "B", followed anyplace
// by two consecutive "o"'s
if("Bob Hood" == s~^B.*oo~)
{
...
Regular expressions can also be used to perform search-and-replace operations on character strings. This mechanism is accessed using the "r~~~" operator. This operator instructs LScript to match the pattern provided, and to replace it with the character(s) provided. In order to access the search-and-replace mechanism, the new search-and-replace assignment operator "~=" is used:
// a sed-like search-and-replace using the s/r operator
if((input = File("nfa.c","r")) == nil)
return;
if((output = File("nfa.bak","w")) == nil)
return;
while(!input.eof())
{
line = input.read();
// replace any "PRIVATE" strings found
// at the start of the line (^) with
// the characters "static "
line ~= r~^PRIVATE~static ~;
output.writeln(line);
}
input.close();
output.close();
Regular expression patterns can be assigned to variables, and those variables used in their place:
// a sed-like search and replace using the s/r operator
if((input = File("nfa.c","r")) == nil)
return;
if((output = File("nfa.bak","w")) == nil)
return;
sr = r~^PRIVATE~static ~;
while(!input.eof())
{
line = input.read();
line ~= sr;
output.writeln(line);
}
input.close();
output.close();
LScript can also construct regular expressions from character strings using the new regexp() function. This can be useful for allowing users to enter regular expression patterns to be used:
// display lines in a file that begin with the letters "PUB"
// compile a regular expression to be used
expr = regexp("^PUB");
// regexp() returns 'nil' if the expression fails to compile
if(expr == nil)
return;
if((file = File("nfa.c","r")) == nil)
return;
while(!file.eof())
{
line = file.read();
if(line == expr)
info(line);
}
Regular expressions also recognize the 'this' container
...
while(!file.eof())
{
file.read();
if(expr)
info();
}
...