What is regex?

A regex (derived from 'regular expression') is a character sequence that define a pattern to be found in some source text. The String package has some functions that allow you to use regexes, like split(), replace() and allMatches(). Xill uses the Java implementation of regex.

Example

Say you want to extract filenames from full file Windows paths. It is not hard to think of an extraction pattern for this, because the file name always comes after the last backslash. The regex pattern would therefore be .*\\\\(.*).

  • .* matches the start of the string until as far as possible
  • \\\\ matches a backslash, which is double escaped; once for the Xill string and once because a literal backslash in a (Java) regex needs to be escaped as well. It will be the last backslash because of the .* in front of it.
  • (.*) matches everything behind the last backslash. It has parentheses because it is the part you want to keep.
use System,File,String;

var files = File.iterateFiles("D:/temp");
foreach(filepath in files) {
var regXResult = String.regex(filepath,".*\\\\(.*)");
var filename = regXResult[1];
    System.print(filename);
}

The result of String.regex will always be either null or a list of matches. This is why the second line in the foreach is necessary.

You could also use String.replace instead, and replace the part you don't want with an empty string. This is usually a bit shorter:

use System,File,String;

var files = File.iterateFiles("D:/temp");
foreach(filepath in files) {
var filename = String.replace(filepath,".*\\\\","");
// var filename = String.replace(filepath,".*\\\\(.*)","$1"); // this would have the same result
System.print(filename);
}

Learn the syntax

There are many resources that can teach you to become a regex master. One of the most extensive is regular-expressions.info. RegexOne provides tutorials and RegexPlanet can be used to test your regex so you'll know it works before using it in Xill.

Visit regular-expressions.info
Visit RegexOne.com
Visit RegexPlanet