compile(pattern: string) - > Result<Regex, string>- 수신자
- 해당 없음
- 최소 인자 수
- 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.
관련 규칙 · Compile the Unicode regular expression language →결과
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
링크Compile the Unicode regular expression language
링크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
링크import std.regex { Regex }import std.iomatch (Regex.compile("^(?:ab)+[0-9]?$")) {case Ok(pattern) => {let present = pattern.isMatch("abab2")let absent = pattern.isMatch("zabab2")io.writeLine("{present}")io.writeLine("{absent}")}case Err(_) => io.writeLine("compile failed")}
true
false
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
truefalse
Return errors for malformed and unsupported pattern syntax
링크import std.regex { Regex }import std.iofor text in (["[", "(", "a**", "[z-a]", "(?=a)", "(?<a>x)(?<a>y)", "\\q"]) {match (Regex.compile(text)) {case Err(message) => io.writeLine("{message != ""}")case Ok(_) => io.writeLine("accepted")}}
true
true
true
true
true
true
true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
truetruetruetruetruetruetrue
Match bounded repetition
링크import std.regex { Regex }import std.iomatch (Regex.compile("a\{2,3\}")) {case Ok(pattern) => {match (pattern.find("aaaa")) {case Some(found) => io.writeLine(found.text)case None() => io.writeLine("no match")}}case Err(_) => io.writeLine("compile failed")}
aaa
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
aaa
Choose the shortest successful lazy repetition
링크import std.regex { Regex }import std.iomatch (Regex.compile("a+?")) {case Ok(pattern) => {match (pattern.find("aaa")) {case Some(found) => io.writeLine(found.text)case None() => io.writeLine("no match")}}case Err(_) => io.writeLine("compile failed")}
a
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
a
Apply scoped case, line, and dot flags
링크import std.regex { Regex }import std.iofunction show(patternText: string, text: string) -> () {match (Regex.compile(patternText)) {case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")case Err(_) => io.writeLine("compile failed")}}show("(?i:ab)", "AB")show("(?m:^b$)", "a\nb\nc")show("(?s:a.b)", "a\nb")show("(?i:σ)", "ς")show("(?i:ss)", "ß")
true
true
true
true
false
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
truetruetruetruefalse
Use Unicode digit, word, and whitespace classes
링크import std.regex { Regex }import std.iofunction show(patternText: string, text: string) -> () {match (Regex.compile(patternText)) {case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")case Err(_) => io.writeLine("compile failed")}}show("^\\d+$", "١٢")show("^\\w+$", "한")show("^\\s$", " ")
true
true
true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
truetruetrue
Match a Unicode general category
링크import std.regex { Regex }import std.iomatch (Regex.compile("^\\p\{Letter\}+$")) {case Ok(pattern) => {let present = pattern.isMatch("한α")io.writeLine("{present}")}case Err(_) => io.writeLine("compile failed")}
true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
true
Use complemented classes and zero-width assertions
링크import std.regex { Regex }import std.iofunction show(patternText: string, text: string) -> () {match (Regex.compile(patternText)) {case Ok(pattern) => io.writeLine("{pattern.isMatch(text)}")case Err(_) => io.writeLine("compile failed")}}show("^\\D+$", "abc")show("\\Aab\\z", "ab")show("\\bcat\\b", "a cat!")
true
true
true
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
truetruetrue
Use one named capture spelling
링크import std.regex { Regex }import std.iofor text in (["(?<word>a)", "(?P<word>a)"]) {match (Regex.compile(text)) {case Ok(_) => io.writeLine("accepted")case Err(_) => io.writeLine("invalid pattern")}}
accepted
invalid pattern
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
acceptedinvalid pattern
Reject a backreference instead of interpreting it as a literal
링크import std.regex { Regex }import std.iomatch (Regex.compile("(a)\\1")) {case Err(_) => io.writeLine("invalid pattern")case Ok(_) => io.writeLine("accepted")}
invalid pattern
기대 결과
기대 결과
실행을 마칩니다. 종료 코드 0.
invalid pattern