Regular Expressions in Chapel

Chapel provides built-in support for regular expressions through its Regex module. Here are some examples of common regexp-related tasks in Chapel.

use Regex;
use IO;

proc main() {
    // This tests whether a pattern matches a string.
    var match = "peach".matches(re"p([a-z]+)ch");
    writeln(match);

    // For other regexp tasks, you'll need to create a Regex object.
    var r = re"p([a-z]+)ch";

    // Many methods are available on these objects. Here's
    // a match test like we saw earlier.
    writeln(r.matches("peach"));

    // This finds the match for the regexp.
    writeln(r.match("peach punch"));

    // This also finds the first match but returns the
    // start and end indexes for the match instead of the
    // matching text.
    var (start, end) = r.find("peach punch");
    writeln("idx: ", start, "..", end);

    // The `captures` method includes information about
    // both the whole-pattern matches and the submatches
    // within those matches.
    var captures = r.captures("peach punch");
    writeln(captures);

    // To find all matches for a regexp:
    var allMatches = r.matches("peach punch pinch");
    writeln(allMatches);

    // Providing a non-negative integer as the maxCount
    // argument to these functions will limit the number
    // of matches.
    allMatches = r.matches("peach punch pinch", maxCount=2);
    writeln(allMatches);

    // The Regex module can also be used to replace
    // subsets of strings with other values.
    var replaced = r.sub("a peach", "<fruit>");
    writeln(replaced);

    // The `sub` method allows you to transform matched
    // text with a given function.
    replaced = r.sub("a peach", (m) => m.toUpper());
    writeln(replaced);
}

To run the program, save it as regular-expressions.chpl and use the Chapel compiler:

$ chpl regular-expressions.chpl -o regular-expressions
$ ./regular-expressions
true
true
peach
idx: 0..5
(peach, ea)
(peach, punch, pinch)
(peach, punch)
a <fruit>
a PEACH

Chapel’s Regex module provides a robust set of tools for working with regular expressions. While the syntax and method names might differ slightly from other languages, the core concepts remain the same. The Regex module in Chapel offers functionality similar to what you might find in other programming languages’ regular expression libraries.

For a complete reference on Chapel regular expressions, check the Regex module documentation in the Chapel language specification.