Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека · std.regex

    Regex.compile

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

    compile(pattern: string) -> Result<Regex, string>
    Модуль
    std.regex →
    Получатель
    Неприменимо
    Минимальное число аргументов
    1
    Максимальное число аргументов
    1

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    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.

    Получатель

    Ограничения параметров

    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.

    Результат

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

    Эффекты

    Ошибки

    Result and effects

    Ссылка

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

    Resolved contracts

    Ссылка

    Related entries

    Ссылка

    std.regex →

    Compile the Unicode regular expression language

    Ссылка
    Правилоtopaz.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.

    Причина

    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.

    Compile literals, classes, grouping, and anchors

    Ссылка
    main.tpzCompile literals, classes, grouping, and anchorsОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    true
    false
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true
    2. false

    Return errors for malformed and unsupported pattern syntax

    Ссылка
    main.tpzReturn errors for malformed and unsupported pattern syntaxОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    true
    true
    true
    true
    true
    true
    true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true
    2. true
    3. true
    4. true
    5. true
    6. true
    7. true

    Match bounded repetition

    Ссылка
    main.tpzMatch bounded repetitionОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    aaa
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. aaa

    Choose the shortest successful lazy repetition

    Ссылка
    main.tpzChoose the shortest successful lazy repetitionОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    a
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. a

    Apply scoped case, line, and dot flags

    Ссылка
    main.tpzApply scoped case, line, and dot flagsОткрыть песочницу →
    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)", "ß")
    Ожидаемый выводКод завершения 0
    true
    true
    true
    true
    false
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true
    2. true
    3. true
    4. true
    5. false

    Use Unicode digit, word, and whitespace classes

    Ссылка
    main.tpzUse Unicode digit, word, and whitespace classesОткрыть песочницу →
    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$", " ")
    Ожидаемый выводКод завершения 0
    true
    true
    true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true
    2. true
    3. true

    Match a Unicode general category

    Ссылка
    main.tpzMatch a Unicode general categoryОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true

    Use complemented classes and zero-width assertions

    Ссылка
    main.tpzUse complemented classes and zero-width assertionsОткрыть песочницу →
    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!")
    Ожидаемый выводКод завершения 0
    true
    true
    true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. true
    2. true
    3. true

    Use one named capture spelling

    Ссылка
    main.tpzUse one named capture spellingОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    accepted
    invalid pattern
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. accepted
    2. invalid pattern

    Reject a backreference instead of interpreting it as a literal

    Ссылка
    main.tpzReject a backreference instead of interpreting it as a literalОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    invalid pattern
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. invalid pattern

    Меню

    Загрузка →