Skip to content
Topaz6.0 · Before release
Download

Search documentation

Specification 6.0 · Not released · Tested product 5.21.3

Use arrow keys to choose a result. Press Enter to open.

Type an API name, diagnostic number, rule, or project topic.

    Library · std.regex

    Regex.compile

    Compiles the Unicode regular expression language and returns Err for invalid patterns.

    compile(pattern: string) -> Result<Regex, string>
    Module
    std.regex
    Receiver
    Not applicable
    Minimum arity
    1
    Maximum arity
    1

    Declaration and parameters

    Link

    Availability

    Included by default: Pending

    Import std.regex in language mode 5.21.

    The current compiler selects std/regex.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Source evidence

    Receiver

    Parameter constraints

    Regex.compile evaluates its pattern string once and returns Ok containing an immutable compiled pattern. Malformed or unsupported syntax returns Err containing a nonempty explanatory string. Compile errors are data and do not issue a diagnostic. Error wording has no fixed spelling.

    Patterns match Unicode scalar values without Unicode normalization. Ordinary characters match themselves. Dot matches any scalar except a line feed. Concatenation, ordered alternation with a vertical bar, capturing groups, and noncapturing groups are supported. The empty pattern and empty alternatives are valid.

    Character classes support literal members, inclusive scalar ranges, and a leading caret for negation. An inverted range is invalid. Escape a metacharacter with a backslash to match it literally. The escapes for n, r, and t match line feed, carriage return, and tab.

    The quantifiers *, +, and ? mean zero or more, one or more, and zero or one. Counted forms {m}, {m,}, and {m,n} use nonnegative decimal counts with m no greater than n. A following question mark makes a repetition lazy. Unescaped braces outside classes delimit a repetition. Quantifiers require an atom and cannot directly repeat an anchor. Possessive quantifiers are invalid.

    A caret and dollar anchor the beginning and end of the input. The escapes \A and \z keep those whole-input meanings. Inline flags i, m, and s select Unicode simple case folding, line anchors, and dot matching line feeds. The forms (?flags) and (?flags:pattern) set flags for the remaining group or a nested group. A minus sign clears subsequent flags.

    Case folding uses the C and S mappings in Unicode 16.0 CaseFolding.txt and excludes the locale-specific T mappings and multiscalar F mappings. The m flag also permits a caret after a line feed and a dollar before a line feed. It does not remove a carriage return before that line feed.

    Unicode properties use Unicode 16.0. The class \d is Decimal_Number. The class \s is White_Space. The class \w combines Alphabetic, Mark, Decimal_Number, Connector_Punctuation, and Join_Control. Uppercase D, S, and W negate those classes. The escapes \b and \B test a boundary or nonboundary between word and nonword scalars. Missing text at either end is nonword.

    The forms \p{name} and \P{name} match or negate a Unicode general category, script, or binary property. Use a category alias, a binary-property alias, or Script= followed by a script alias. Names use Unicode 16.0 aliases and ignore case, spaces, and underscores. An unknown property or value is invalid. Unicode matching cannot be disabled to match a partial UTF-8 sequence.

    Named captures use (?<name>pattern). Names are case sensitive unique ASCII identifiers beginning with a letter or underscore and continuing with letters, digits, or underscores. The alternative spelling (?P<name>pattern) is invalid.

    Backreferences, lookaround, conditionals, atomic groups, and unknown alphanumeric escapes are invalid. Compile performs no I/O and never changes the pattern string.

    Result

    The declared result type is Result<Regex, string>.

    Effects

    Failures

    Result and effects

    Link

    Compiles the Unicode regular expression language and returns Err for invalid patterns.

    Resolved contracts

    Link

    Related entries

    Link

    std.regex

    Compile the Unicode regular expression language

    Link
    Ruletopaz.stdlib.contract.regex-compile.rule

    Compile the Unicode regular expression language

    Regex.compile evaluates its pattern string once and returns Ok containing an immutable compiled pattern. Malformed or unsupported syntax returns Err containing a nonempty explanatory string. Compile errors are data and do not issue a diagnostic. Error wording has no fixed spelling.

    Patterns match Unicode scalar values without Unicode normalization. Ordinary characters match themselves. Dot matches any scalar except a line feed. Concatenation, ordered alternation with a vertical bar, capturing groups, and noncapturing groups are supported. The empty pattern and empty alternatives are valid.

    Character classes support literal members, inclusive scalar ranges, and a leading caret for negation. An inverted range is invalid. Escape a metacharacter with a backslash to match it literally. The escapes for n, r, and t match line feed, carriage return, and tab.

    The quantifiers *, +, and ? mean zero or more, one or more, and zero or one. Counted forms {m}, {m,}, and {m,n} use nonnegative decimal counts with m no greater than n. A following question mark makes a repetition lazy. Unescaped braces outside classes delimit a repetition. Quantifiers require an atom and cannot directly repeat an anchor. Possessive quantifiers are invalid.

    A caret and dollar anchor the beginning and end of the input. The escapes \A and \z keep those whole-input meanings. Inline flags i, m, and s select Unicode simple case folding, line anchors, and dot matching line feeds. The forms (?flags) and (?flags:pattern) set flags for the remaining group or a nested group. A minus sign clears subsequent flags.

    Case folding uses the C and S mappings in Unicode 16.0 CaseFolding.txt and excludes the locale-specific T mappings and multiscalar F mappings. The m flag also permits a caret after a line feed and a dollar before a line feed. It does not remove a carriage return before that line feed.

    Unicode properties use Unicode 16.0. The class \d is Decimal_Number. The class \s is White_Space. The class \w combines Alphabetic, Mark, Decimal_Number, Connector_Punctuation, and Join_Control. Uppercase D, S, and W negate those classes. The escapes \b and \B test a boundary or nonboundary between word and nonword scalars. Missing text at either end is nonword.

    The forms \p{name} and \P{name} match or negate a Unicode general category, script, or binary property. Use a category alias, a binary-property alias, or Script= followed by a script alias. Names use Unicode 16.0 aliases and ignore case, spaces, and underscores. An unknown property or value is invalid. Unicode matching cannot be disabled to match a partial UTF-8 sequence.

    Named captures use (?<name>pattern). Names are case sensitive unique ASCII identifiers beginning with a letter or underscore and continuing with letters, digits, or underscores. The alternative spelling (?P<name>pattern) is invalid.

    Backreferences, lookaround, conditionals, atomic groups, and unknown alphanumeric escapes are invalid. Compile performs no I/O and never changes the pattern string.

    Why

    A documented Unicode pattern language handles text independently of its UTF-8 encoding. Unicode 16.0 aligns property tests with the text library edition. Simple case folding compares scalars without inserting extra characters or depending on a locale. Excluding backreferences and lookaround preserves a regular language. One named capture spelling avoids an alias while compile errors let applications validate patterns as input.

    Source evidence

    Compile literals, classes, grouping, and anchors

    Link
    main.tpzCompile literals, classes, grouping, and anchorsOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("^(?:ab)+[0-9]?$")) {
    4. case Ok(pattern) => {
    5. let present = pattern.isMatch("abab2")
    6. let absent = pattern.isMatch("zabab2")
    7. io.writeLine("{present}")
    8. io.writeLine("{absent}")
    9. }
    10. case Err(_) => io.writeLine("compile failed")
    11. }
    Expected outputexit 0
    true
    false
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. true
    2. false
    Source evidence

    Return errors for malformed and unsupported pattern syntax

    Link
    main.tpzReturn errors for malformed and unsupported pattern syntaxOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. for text in (["[", "(", "a**", "[z-a]", "(?=a)", "(?<a>x)(?<a>y)", "\\q"]) {
    4. match (Regex.compile(text)) {
    5. case Err(message) => io.writeLine("{message != ""}")
    6. case Ok(_) => io.writeLine("accepted")
    7. }
    8. }
    Expected outputexit 0
    true
    true
    true
    true
    true
    true
    true
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. true
    2. true
    3. true
    4. true
    5. true
    6. true
    7. true
    Source evidence

    Match bounded repetition

    Link
    main.tpzMatch bounded repetitionOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("a\{2,3\}")) {
    4. case Ok(pattern) => {
    5. match (pattern.find("aaaa")) {
    6. case Some(found) => io.writeLine(found.text)
    7. case None() => io.writeLine("no match")
    8. }
    9. }
    10. case Err(_) => io.writeLine("compile failed")
    11. }
    Expected outputexit 0
    aaa
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. aaa
    Source evidence

    Choose the shortest successful lazy repetition

    Link
    main.tpzChoose the shortest successful lazy repetitionOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("a+?")) {
    4. case Ok(pattern) => {
    5. match (pattern.find("aaa")) {
    6. case Some(found) => io.writeLine(found.text)
    7. case None() => io.writeLine("no match")
    8. }
    9. }
    10. case Err(_) => io.writeLine("compile failed")
    11. }
    Expected outputexit 0
    a
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. a
    Source evidence

    Apply scoped case, line, and dot flags

    Link
    main.tpzApply scoped case, line, and dot flagsOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. function show(patternText: string, text: string) -> () {
    4. match (Regex.compile(patternText)) {
    5. case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")
    6. case Err(_) => io.writeLine("compile failed")
    7. }
    8. }
    9. show("(?i:ab)", "AB")
    10. show("(?m:^b$)", "a\nb\nc")
    11. show("(?s:a.b)", "a\nb")
    12. show("(?i:σ)", "ς")
    13. show("(?i:ss)", "ß")
    Expected outputexit 0
    true
    true
    true
    true
    false
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. true
    2. true
    3. true
    4. true
    5. false
    Source evidence

    Use Unicode digit, word, and whitespace classes

    Link
    main.tpzUse Unicode digit, word, and whitespace classesOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. function show(patternText: string, text: string) -> () {
    4. match (Regex.compile(patternText)) {
    5. case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")
    6. case Err(_) => io.writeLine("compile failed")
    7. }
    8. }
    9. show("^\\d+$", "١٢")
    10. show("^\\w+$", "한")
    11. show("^\\s$", " ")
    Expected outputexit 0
    true
    true
    true
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. true
    2. true
    3. true
    Source evidence

    Match a Unicode general category

    Link
    main.tpzMatch a Unicode general categoryOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("^\\p\{Letter\}+$")) {
    4. case Ok(pattern) => {
    5. let present = pattern.isMatch("한α")
    6. io.writeLine("{present}")
    7. }
    8. case Err(_) => io.writeLine("compile failed")
    9. }
    Expected outputexit 0
    true
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. true
    Source evidence

    Use complemented classes and zero-width assertions

    Link
    main.tpzUse complemented classes and zero-width assertionsOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. function show(patternText: string, text: string) -> () {
    4. match (Regex.compile(patternText)) {
    5. case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")
    6. case Err(_) => io.writeLine("compile failed")
    7. }
    8. }
    9. show("^\\D+$", "abc")
    10. show("\\Aab\\z", "ab")
    11. show("\\bcat\\b", "a cat!")
    Expected outputexit 0
    true
    true
    true
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. true
    2. true
    3. true
    Source evidence

    Use one named capture spelling

    Link
    main.tpzUse one named capture spellingOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. for text in (["(?<word>a)", "(?P<word>a)"]) {
    4. match (Regex.compile(text)) {
    5. case Ok(_) => io.writeLine("accepted")
    6. case Err(_) => io.writeLine("invalid pattern")
    7. }
    8. }
    Expected outputexit 0
    accepted
    invalid pattern
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. accepted
    2. invalid pattern
    Source evidence

    Reject a backreference instead of interpreting it as a literal

    Link
    main.tpzReject a backreference instead of interpreting it as a literalOpen in Playground
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("(a)\\1")) {
    4. case Err(_) => io.writeLine("invalid pattern")
    5. case Ok(_) => io.writeLine("accepted")
    6. }
    Expected outputexit 0
    invalid pattern
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. invalid pattern
    Source evidence

    Menu

    Download