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

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

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

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

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

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

    Match.named

    An independent map of participating named captures, including captured empty strings.

    Match.named: Map<string, string>
    Модуль
    std.regex →
    Получатель
    Match
    Минимальное число аргументов
    0
    Максимальное число аргументов
    0

    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.

    Получатель

    Match

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

    Match.start and Match.end are read-only nonnegative UTF-8 byte offsets in the original input. They follow the inclusive start and exclusive end of byte intervals. Both are scalar boundaries and the end does not exceed the UTF-8 byte length of the input.

    Match.text is the matched substring. An empty match has equal start and end and an empty text value. The offsets are not string grapheme indexes. A match may select a combining mark inside a grapheme.

    Encoding the original input with encodeUtf8, slicing its bytes from start to end, and calling decodeUtf8 returns Ok containing Match.text. This relationship also holds for non-ASCII input.

    Match.groups returns an independent array indexed by capture number. Entry zero is Some containing the entire match. Capturing parentheses are numbered from one in opening-parenthesis order. Named groups participate in the same numbering and noncapturing groups do not.

    A nonparticipating capture has value None(). A participating empty capture has value Some containing an empty string. A repeated capture retains the last participating capture in the selected match.

    Match.named returns an independent map from capture names to captured strings. A nonparticipating named capture is absent. A participating empty named capture is present with an empty string. Names are inserted in ascending ASCII order.

    Reading a Match field evaluates its receiver once and does not modify the Match or input. Mutating a groups array or named map does not affect a later field read. Field access cannot fail for a Match value.

    Результат

    The declared result type is Map<string, string>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Select this field from a value of its named type without call parentheses.

    An independent map of participating named captures, including captured empty strings.

    Resolved contracts

    Ссылка

    Related entries

    Ссылка

    std.regex →

    Read match boundaries and capture snapshots

    Ссылка
    Правилоtopaz.stdlib.contract.regex-match.rule

    Read match boundaries and capture snapshots

    Match.start and Match.end are read-only nonnegative UTF-8 byte offsets in the original input. They follow the inclusive start and exclusive end of byte intervals. Both are scalar boundaries and the end does not exceed the UTF-8 byte length of the input.

    Match.text is the matched substring. An empty match has equal start and end and an empty text value. The offsets are not string grapheme indexes. A match may select a combining mark inside a grapheme.

    Encoding the original input with encodeUtf8, slicing its bytes from start to end, and calling decodeUtf8 returns Ok containing Match.text. This relationship also holds for non-ASCII input.

    Match.groups returns an independent array indexed by capture number. Entry zero is Some containing the entire match. Capturing parentheses are numbered from one in opening-parenthesis order. Named groups participate in the same numbering and noncapturing groups do not.

    A nonparticipating capture has value None(). A participating empty capture has value Some containing an empty string. A repeated capture retains the last participating capture in the selected match.

    Match.named returns an independent map from capture names to captured strings. A nonparticipating named capture is absent. A participating empty named capture is present with an empty string. Names are inserted in ascending ASCII order.

    Reading a Match field evaluates its receiver once and does not modify the Match or input. Mutating a groups array or named map does not affect a later field read. Field access cannot fail for a Match value.

    Причина

    Byte offsets identify every exact match even when a pattern selects part of a grapheme. The byte-slice relationship makes those offsets usable without confusing them with text indexing. Optional numbered captures and omitted named entries distinguish absence from a captured empty string.

    Report UTF-8 byte offsets for non-ASCII matches

    Ссылка
    main.tpzReport UTF-8 byte offsets for non-ASCII matchesОткрыть песочницу →
    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) => {
    6. match (pattern.find(text)) {
    7. case Some(found) => io.writeLine("{found.start}:{found.end}:{found.text}")
    8. case None() => io.writeLine("no match")
    9. }
    10. }
    11. case Err(_) => io.writeLine("compile failed")
    12. }
    13. }
    14. show("한", "é한🙂")
    15. show("́", "éx")
    Ожидаемый выводКод завершения 0
    2:5:한
    1:3:́
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. 2:5:한
    2. 1:3:́

    Recover a match through the byte slice identified by its offsets

    Ссылка
    main.tpzRecover a match through the byte slice identified by its offsetsОткрыть песочницу →
    1. import std.regex { Regex }
    2. import std.io
    3. let text = "한x"
    4. match (Regex.compile("한")) {
    5. case Ok(pattern) => {
    6. match (pattern.find(text)) {
    7. case Some(found) => {
    8. let bytes = text.encodeUtf8().slice(found.start, found.end)
    9. match (bytes.decodeUtf8()) {
    10. case Ok(decoded) => io.writeLine(decoded)
    11. case Err(_) => io.writeLine("invalid UTF-8 slice")
    12. }
    13. }
    14. case None() => io.writeLine("no match")
    15. }
    16. }
    17. case Err(_) => io.writeLine("compile failed")
    18. }
    Ожидаемый выводКод завершения 0
    한
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Keep capture zero and distinguish missing and empty captures

    Ссылка
    main.tpzKeep capture zero and distinguish missing and empty capturesОткрыть песочницу →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("(?<word>a)(b)?()")) {
    4. case Ok(pattern) => {
    5. match (pattern.find("a")) {
    6. case Some(found) => {
    7. io.writeLine("{found.groups.length}")
    8. for group in (found.groups) {
    9. match (group) {
    10. case Some(text) => io.writeLine("some={text}")
    11. case None() => io.writeLine("none")
    12. }
    13. }
    14. }
    15. case None() => io.writeLine("no match")
    16. }
    17. }
    18. case Err(_) => io.writeLine("compile failed")
    19. }
    Ожидаемый выводКод завершения 0
    4
    some=a
    some=a
    none
    some=
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. 4
    2. some=a
    3. some=a
    4. none
    5. some=

    Omit absent named captures and retain a captured empty string

    Ссылка
    main.tpzOmit absent named captures and retain a captured empty stringОткрыть песочницу →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("(?<z>a)?(?<a>b*)")) {
    4. case Ok(pattern) => {
    5. match (pattern.find("")) {
    6. case Some(found) => {
    7. let mut snapshot = found.named
    8. let hasOptional = snapshot.containsKey("z")
    9. io.writeLine("{hasOptional}")
    10. match (snapshot.get("a")) {
    11. case Some(text) => io.writeLine("some={text}")
    12. case None() => io.writeLine("none")
    13. }
    14. snapshot.insert("a", "changed")
    15. match (found.named.get("a")) {
    16. case Some(text) => io.writeLine("again={text}")
    17. case None() => io.writeLine("none")
    18. }
    19. }
    20. case None() => io.writeLine("no match")
    21. }
    22. }
    23. case Err(_) => io.writeLine("compile failed")
    24. }
    Ожидаемый выводКод завершения 0
    false
    some=
    again=
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. false
    2. some=
    3. again=

    Меню

    Загрузка →