본문으로 건너뛰기
토파즈6.0 · 출시 전
다운로드 →

문서 검색

명세 6.0

방향키로 결과를 고르고 Enter를 눌러 여세요.

API 이름, 진단 번호, 규칙 또는 프로젝트 주제를 입력하세요.

    라이브러리

    std.regex

    Compile patterns, search strings, and inspect Match values.

    이 모듈의 API

    11개 API

    이름모듈
    Match.end →std.regex →
    Match.groups →std.regex →
    Match.named →std.regex →
    Match.start →std.regex →
    Match.text →std.regex →
    Regex.compile →std.regex →
    Regex.find →std.regex →
    Regex.findAll →std.regex →
    Regex.isMatch →std.regex →
    Regex.replaceAll →std.regex →
    Regex.split →std.regex →

    Module

    링크

    Regex.compile validates a Unicode pattern before searching, splitting, or replacing text. Match values contain UTF-8 byte boundaries and independent capture snapshots.

    Why

    링크

    A compiled pattern keeps one search language and one match sequence across Boolean searches, match extraction, splitting, and replacement.

    Availability

    링크

    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.

    Exported types

    링크

    export type Regex = Regex

    export type Match = Match

    Type members keep the compiler-owned type name shown in their declarations. Importing a module does not create a new type identity.

    Public API

    링크

    Match.end →

    Match.groups →

    Match.named →

    Match.start →

    Match.text →

    Regex.compile →

    Regex.find →

    Regex.findAll →

    Regex.isMatch →

    Regex.replaceAll →

    Regex.split →

    Pending contracts

    링크

    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
    링크
    규칙topaz.stdlib.contract.regex-search.rule

    Search from the left and advance through nonoverlapping matches

    Regex.isMatch reports whether a match exists anywhere in the input. Regex.find returns Some containing the first match or None() when no match exists. Regex.findAll returns every nonoverlapping match in search order and returns an empty array when no match exists.

    Search begins at the earliest Unicode scalar boundary that permits the complete pattern to match. At that position alternatives are tried in pattern order. Greedy repetitions prefer more scalars and lazy repetitions prefer fewer scalars while still allowing the rest of the pattern to match.

    After a nonempty match, findAll resumes at its exclusive end. After an empty match, it resumes at the next Unicode scalar boundary. An empty match directly at the end of the preceding nonempty match is skipped and search advances to the next scalar boundary.

    An empty pattern visits every scalar boundary, including both ends. The empty input has one boundary and produces one empty match for an empty pattern. Matching never splits the UTF-8 bytes of a scalar.

    Regex.split and Regex.replaceAll use the same ordered match sequence as findAll. Repeated calls start a new search and do not retain a cursor. The input string and compiled pattern are unchanged.

    The receiver is evaluated once before the positional arguments, which are evaluated once from left to right. Search does not invoke user callbacks or access external state. No match is an ordinary result and does not produce a diagnostic.

    이유

    One ordered match sequence makes searching, splitting, and replacement agree. Advancing after an empty match ensures progress without splitting a Unicode scalar. Boolean search is distinct from extracting Match data and does not introduce regex membership through the in operator.

    Choose the first successful alternative at the leftmost position

    링크
    main.tpzChoose the first successful alternative at the leftmost position플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("a|ab")) {
    4. case Ok(pattern) => {
    5. match (pattern.find("zab")) {
    6. case Some(found) => io.writeLine("{found.start}:{found.end}:{found.text}")
    7. case None() => io.writeLine("no match")
    8. }
    9. let present = pattern.isMatch("zab")
    10. let absent = pattern.isMatch("zzz")
    11. io.writeLine("{present}:{absent}")
    12. match (pattern.find("zzz")) {
    13. case None() => io.writeLine("none")
    14. case Some(_) => io.writeLine("present")
    15. }
    16. let matches = pattern.findAll("zzz")
    17. io.writeLine("{matches.length}")
    18. }
    19. case Err(_) => io.writeLine("compile failed")
    20. }
    기대 출력종료 코드 0
    1:2:a
    true:false
    none
    0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 1:2:a
    2. true:false
    3. none
    4. 0

    Choose a group alternative that allows the complete pattern to match

    링크
    main.tpzChoose a group alternative that allows the complete pattern to match플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("(a|ab)c")) {
    4. case Ok(pattern) => {
    5. match (pattern.find("abc")) {
    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
    abc
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. abc

    Return nonoverlapping matches in input order

    링크
    main.tpzReturn nonoverlapping matches in input order플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("aa")) {
    4. case Ok(pattern) => {
    5. for found in (pattern.findAll("aaaaa")) {
    6. io.writeLine("{found.start}:{found.end}:{found.text}")
    7. }
    8. }
    9. case Err(_) => io.writeLine("compile failed")
    10. }
    기대 출력종료 코드 0
    0:2:aa
    2:4:aa
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 0:2:aa
    2. 2:4:aa

    Visit each boundary for an empty pattern and the empty input

    링크
    main.tpzVisit each boundary for an empty pattern and the empty input플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("")) {
    4. case Ok(pattern) => {
    5. for found in (pattern.findAll("ab")) {
    6. io.writeLine("{found.start}:{found.end}")
    7. }
    8. io.writeLine("empty input")
    9. for found in (pattern.findAll("")) {
    10. io.writeLine("{found.start}:{found.end}")
    11. }
    12. }
    13. case Err(_) => io.writeLine("compile failed")
    14. }
    기대 출력종료 코드 0
    0:0
    1:1
    2:2
    empty input
    0:0
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 0:0
    2. 1:1
    3. 2:2
    4. empty input
    5. 0:0

    Skip an empty match directly after a nonempty match

    링크
    main.tpzSkip an empty match directly after a nonempty match플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("a*")) {
    4. case Ok(pattern) => {
    5. for found in (pattern.findAll("ab")) {
    6. io.writeLine("{found.start}:{found.end}:{found.text}")
    7. }
    8. }
    9. case Err(_) => io.writeLine("compile failed")
    10. }
    기대 출력종료 코드 0
    0:1:a
    2:2:
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. 0:1:a
    2. 2:2:

    Return no match after scanning a longer valid input

    링크
    main.tpzReturn no match after scanning a longer valid input플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. let mut text = "a"
    4. for step in (0 .. 17) {
    5. text = text + text
    6. }
    7. match (Regex.compile("z")) {
    8. case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")
    9. case Err(_) => io.writeLine("compile failed")
    10. }
    기대 출력종료 코드 0
    false
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. false

    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=

    Split and replace using the shared match sequence

    링크
    규칙topaz.stdlib.contract.regex-transform.rule

    Split and replace using the shared match sequence

    Regex.split returns the input portions between the matches selected by findAll. Delimiters disappear and capture groups are not inserted. Empty portions at either end and between adjacent delimiters are retained. No match produces an array containing the original input.

    Regex.replaceAll replaces the same nonoverlapping matches while copying all text between them unchanged. No match returns the original text. The operation does not search inserted replacement text.

    Replacement references use a dollar sign followed by a braced capture number or name. Capture zero denotes the complete match. An unknown or nonparticipating capture expands to an empty string. Two dollar signs produce one literal dollar.

    A replacement selector is a nonnegative decimal capture number or an ASCII capture name. Dollar text that is neither a double dollar nor a well-formed braced selector is literal. Unbraced dollar names and numbers do not form references. Expansion is performed once and captured dollar text is not expanded again.

    An empty pattern splits at every scalar boundary and inserts replacement text at those same boundaries. The adjacent-empty-match rule from findAll also applies when a nonempty match is followed by an empty candidate.

    The receiver is evaluated once before text and replacement arguments, which are evaluated once from left to right. Splitting and replacement leave the original string and Regex unchanged. They have no external effects and do not call a user callback.

    이유

    Using one match sequence prevents a search from disagreeing with a later replacement. Braced capture references have one spelling and an explicit end, so a capture name cannot absorb following replacement text.

    Retain empty split fields without inserting captures

    링크
    main.tpzRetain empty split fields without inserting captures플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("(,)")) {
    4. case Ok(pattern) => {
    5. for field in (pattern.split(",a,,b,")) {
    6. io.writeLine("[{field}]")
    7. }
    8. for field in (pattern.split("plain")) {
    9. io.writeLine("[{field}]")
    10. }
    11. }
    12. case Err(_) => io.writeLine("compile failed")
    13. }
    기대 출력종료 코드 0
    []
    [a]
    []
    [b]
    []
    [plain]
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. []
    2. [a]
    3. []
    4. [b]
    5. []
    6. [plain]

    Expand braced capture references and a literal dollar

    링크
    main.tpzExpand braced capture references and a literal dollar플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("(?<word>[a-z]+)([0-9]+)?")) {
    4. case Ok(pattern) => {
    5. let replacement = "$\{word\}/$\{0\}/$\{2\}/$\{missing\}/$$"
    6. io.writeLine(pattern.replaceAll("a1 b", replacement))
    7. io.writeLine(pattern.replaceAll("123", replacement))
    8. }
    9. case Err(_) => io.writeLine("compile failed")
    10. }
    기대 출력종료 코드 0
    a/a1/1//$ b/b///$
    123
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. a/a1/1//$ b/b///$
    2. 123

    Preserve text that is not a braced reference

    링크
    main.tpzPreserve text that is not a braced reference플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("a")) {
    4. case Ok(pattern) => io.writeLine(pattern.replaceAll("a", "$word $1 $ $\{\} $\{bad-name\}"))
    5. case Err(_) => io.writeLine("compile failed")
    6. }
    기대 출력종료 코드 0
    $word $1 $ ${} ${bad-name}
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. $word $1 $ ${} ${bad-name}

    Split and replace at each empty-pattern boundary

    링크
    main.tpzSplit and replace at each empty-pattern boundary플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("")) {
    4. case Ok(pattern) => {
    5. for field in (pattern.split("ab")) {
    6. io.writeLine("[{field}]")
    7. }
    8. io.writeLine(pattern.replaceAll("ab", "-"))
    9. }
    10. case Err(_) => io.writeLine("compile failed")
    11. }
    기대 출력종료 코드 0
    []
    [a]
    [b]
    []
    -a-b-
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. []
    2. [a]
    3. [b]
    4. []
    5. -a-b-

    Share the adjacent-empty-match rule across transformations

    링크
    main.tpzShare the adjacent-empty-match rule across transformations플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.io
    3. match (Regex.compile("a*")) {
    4. case Ok(pattern) => {
    5. for field in (pattern.split("ab")) {
    6. io.writeLine("[{field}]")
    7. }
    8. io.writeLine(pattern.replaceAll("ab", "-"))
    9. }
    10. case Err(_) => io.writeLine("compile failed")
    11. }
    기대 출력종료 코드 0
    []
    [b]
    []
    -b-
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. []
    2. [b]
    3. []
    4. -b-

    Evaluate receiver and replacement inputs once in source order

    링크
    main.tpzEvaluate receiver and replacement inputs once in source order플레이그라운드 열기 →
    1. import std.regex { Regex }
    2. import std.test
    3. import std.io
    4. function makePattern() -> Regex {
    5. io.writeLine("receiver")
    6. return test.assertOk(Regex.compile("a"))
    7. }
    8. function inputText() -> string {
    9. io.writeLine("text")
    10. return "a"
    11. }
    12. function replacementText() -> string {
    13. io.writeLine("replacement")
    14. return "b"
    15. }
    16. io.writeLine(makePattern().replaceAll(inputText(), replacementText()))
    기대 출력종료 코드 0
    receiver
    text
    replacement
    b
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. receiver
    2. text
    3. replacement
    4. b

    메뉴

    다운로드 →