I was recently asked a question on using regular expressions with ?type , and I thought it was interesting enough, to share here.

The user wanted to identify symbolic functions, whose names matched a certain pattern, using the type command. Moreover, they wanted to do this with regular expressions for the patterns.

This turned out to be pretty easy to do using ?TypeTools,AddType and ?StringTools,RegMatch :

(**) TypeTools[AddType]( regexp,
proc(sym, pat)
local match;
if type(sym, {symbol,string}) and type(pat, {symbol, string})
 and StringTools:-RegMatch(pat, sym, 'match')
 then
if match = convert(sym, string) then
return true;
end if;
end if;
return false;
end proc );

The command above creates a new type that matches symbols or strings that exactly match a given regular expression.

(**) type(myFuncA01, regexp(`[a-zA-Z]+A[0-9]+`));
#                                     true

(**) type(foobar, regexp(`[a-zA-Z]+A[0-9]+`));
#                                     false

Notice that the definition of regexp above checks the arguments sent to StringTools:-RegMatch so that false gets returned instead of an error in case of unexpected inputs. This is necessary so that regexp types will pass a type check for type

(**) type(regexp(`.`), type);
#                                     true

That is important, so that regexp can be used in other structured types (see ?type,structure ). In particular we can use type typefunc to match functions with names matching a pattern:

(**) type(myFuncA01(x,y), typefunc(symbol, regexp(`[a-zA-Z]+A[0-9]+`)) );
#                                     true

(**) type(foobar(x,y), typefunc(anything, regexp(`[a-zA-Z]+A[0-9]+`)) );
#                                     false

(**) type(my2FuncA01(x,y), typefunc(symbol, regexp(`[a-zA-Z]+A[0-9]+`)) );
#                                     false

And many more:

(**) type(x_1 = 10, regexp(`[a-z]+_[0-9]+`)=anything);
#                                     true

(**) type(x_y = 10, regexp(`[a-z]+_[0-9]+`)=anything);
#                                     false

Please Wait...