Package syntax

import "regexp/syntax"
Overview
Index

Overview ▾

包语法将正则表达式解析为解析树,并将解析树编译为程序. 大多数正则表达式客户端将使用regexp程序包(例如Compile and Match)而不是此程序包.

Syntax

使用Perl标志进行解析时,此程序包可以理解的正则表达式语法如下. 通过将替代标志传递给Parse,可以禁用语法的某些部分.

单个字符:

.              any character, possibly including newline (flag s=true)
[xyz]          character class
[^xyz]         negated character class
\d             Perl character class
\D             negated Perl character class
[[:alpha:]]    ASCII character class
[[:^alpha:]]   negated ASCII character class
\pN            Unicode character class (one-letter name)
\p{Greek}      Unicode character class
\PN            negated Unicode character class (one-letter name)
\P{Greek}      negated Unicode character class

Composites:

xy             x followed by y
x|y            x or y (prefer x)

Repetitions:

x*             zero or more x, prefer more
x+             one or more x, prefer more
x?             zero or one x, prefer one
x{n,m}         n or n+1 or ... or m x, prefer more
x{n,}          n or more x, prefer more
x{n}           exactly n x
x*?            zero or more x, prefer fewer
x+?            one or more x, prefer fewer
x??            zero or one x, prefer zero
x{n,m}?        n or n+1 or ... or m x, prefer fewer
x{n,}?         n or more x, prefer fewer
x{n}?          exactly n x

实现限制:计数形式x {n,m},x {n,}和x {n}拒绝创建重复次数超过1000的最小或最大重复形式.无限制重复不受此限制.

Grouping:

(re)           numbered capturing group (submatch)
(?P<name>re)   named & numbered capturing group (submatch)
(?:re)         non-capturing group
(?flags)       set flags within current group; non-capturing
(?flags:re)    set flags during re; non-capturing

Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:

i              case-insensitive (default false)
m              multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)
s              let . match \n (default false)
U              ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)

空字符串:

^              at beginning of text or line (flag m=true)
$              at end of text (like \z not Perl's \Z) or line (flag m=true)
\A             at beginning of text
\b             at ASCII word boundary (\w on one side and \W, \A, or \z on the other)
\B             not at ASCII word boundary
\z             at end of text

转义序列:

\a             bell (== \007)
\f             form feed (== \014)
\t             horizontal tab (== \011)
\n             newline (== \012)
\r             carriage return (== \015)
\v             vertical tab character (== \013)
\*             literal *, for any punctuation character *
\123           octal character code (up to three digits)
\x7F           hex character code (exactly two digits)
\x{10FFFF}     hex character code
\Q...\E        literal text ... even if ... has punctuation

角色类元素:

x              single character
A-Z            character range (inclusive)
\d             Perl character class
[:foo:]        ASCII character class foo
\p{Foo}        Unicode character class Foo
\pF            Unicode character class F (one-letter name)

将字符类命名为字符类元素:

[\d]           digits (== \d)
[^\d]          not digits (== \D)
[\D]           not digits (== \D)
[^\D]          not not digits (== \d)
[[:name:]]     named ASCII class inside character class (== [:name:])
[^[:name:]]    named ASCII class inside negated character class (== [:^name:])
[\p{Name}]     named Unicode property inside character class (== \p{Name})
[^\p{Name}]    named Unicode property inside negated character class (== \P{Name})

Perl字符类(所有仅ASCII):

\d             digits (== [0-9])
\D             not digits (== [^0-9])
\s             whitespace (== [\t\n\f\r ])
\S             not whitespace (== [^\t\n\f\r ])
\w             word characters (== [0-9A-Za-z_])
\W             not word characters (== [^0-9A-Za-z_])

ASCII字符类:

[[:alnum:]]    alphanumeric (== [0-9A-Za-z])
[[:alpha:]]    alphabetic (== [A-Za-z])
[[:ascii:]]    ASCII (== [\x00-\x7F])
[[:blank:]]    blank (== [\t ])
[[:cntrl:]]    control (== [\x00-\x1F\x7F])
[[:digit:]]    digits (== [0-9])
[[:graph:]]    graphical (== [!-~] == [A-Za-z0-9!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])
[[:lower:]]    lower case (== [a-z])
[[:print:]]    printable (== [ -~] == [ [:graph:]])
[[:punct:]]    punctuation (== [!-/:-@[-`{-~])
[[:space:]]    whitespace (== [\t\n\v\f\r ])
[[:upper:]]    upper case (== [A-Z])
[[:word:]]     word characters (== [0-9A-Za-z_])
[[:xdigit:]]   hex digit (== [0-9A-Fa-f])

func IsWordChar

func IsWordChar(r rune) bool

IsWordChar报告在\ b和\ B零宽度断言的评估期间r是否被视为"单词字符". 这些断言仅是ASCII:字字符是[A-Za-z0-9_].

type EmptyOp

EmptyOp指定零宽度断言的一种或混合形式.

type EmptyOp uint8
const (
    EmptyBeginLine EmptyOp = 1 << iota
    EmptyEndLine
    EmptyBeginText
    EmptyEndText
    EmptyWordBoundary
    EmptyNoWordBoundary
)

func EmptyOpContext

func EmptyOpContext(r1, r2 rune) EmptyOp

EmptyOpContext返回在符文r1和r2之间的位置处满足的零宽度断言. 传递r1 == -1表示该位置位于文本的开头. 传递r2 == -1表示该位置在文本的结尾.

type Error

错误描述了无法解析正则表达式并给出有问题的表达式.

type Error struct {
    Code ErrorCode
    Expr string
}

func (*Error) Error

func (e *Error) Error() string

type ErrorCode

ErrorCode描述了解析正则表达式的失败.

type ErrorCode string
const (
    // Unexpected error
    ErrInternalError ErrorCode = "regexp/syntax: internal error"

    // Parse errors
    ErrInvalidCharClass      ErrorCode = "invalid character class"
    ErrInvalidCharRange      ErrorCode = "invalid character class range"
    ErrInvalidEscape         ErrorCode = "invalid escape sequence"
    ErrInvalidNamedCapture   ErrorCode = "invalid named capture"
    ErrInvalidPerlOp         ErrorCode = "invalid or unsupported Perl syntax"
    ErrInvalidRepeatOp       ErrorCode = "invalid nested repetition operator"
    ErrInvalidRepeatSize     ErrorCode = "invalid repeat count"
    ErrInvalidUTF8           ErrorCode = "invalid UTF-8"
    ErrMissingBracket        ErrorCode = "missing closing ]"
    ErrMissingParen          ErrorCode = "missing closing )"
    ErrMissingRepeatArgument ErrorCode = "missing argument to repetition operator"
    ErrTrailingBackslash     ErrorCode = "trailing backslash at end of expression"
    ErrUnexpectedParen       ErrorCode = "unexpected )"
)

func (ErrorCode) String

func (e ErrorCode) String() string

type Flags

标志控制解析器的行为并记录有关regexp上下文的信息.

type Flags uint16
const (
    FoldCase      Flags = 1 << iota // case-insensitive match
    Literal                         // treat pattern as literal string
    ClassNL                         // allow character classes like [^a-z] and [[:space:]] to match newline
    DotNL                           // allow . to match newline
    OneLine                         // treat ^ and $ as only matching at beginning and end of text
    NonGreedy                       // make repetition operators default to non-greedy
    PerlX                           // allow Perl extensions
    UnicodeGroups                   // allow \p{Han}, \P{Han} for Unicode group and negation
    WasDollar                       // regexp OpEndText was $, not \z
    Simple                          // regexp contains no counted repetition

    MatchNL = ClassNL | DotNL

    Perl        = ClassNL | OneLine | PerlX | UnicodeGroups // as close to Perl as possible
    POSIX Flags = 0                                         // POSIX syntax
)

type Inst

Inst是正则表达式程序中的一条指令.

type Inst struct {
    Op   InstOp
    Out  uint32 // all but InstMatch, InstFail
    Arg  uint32 // InstAlt, InstAltMatch, InstCapture, InstEmptyWidth
    Rune []rune
}

func (*Inst) MatchEmptyWidth

func (i *Inst) MatchEmptyWidth(before rune, after rune) bool

MatchEmptyWidth报告指令在前后符文之间是否匹配空字符串. 仅当i.Op == InstEmptyWidth时才应调用它.

func (*Inst) MatchRune

func (i *Inst) MatchRune(r rune) bool

MatchRune报告指令是否匹配(并消耗)r. 仅当i.Op == InstRune时才应调用它.

func (*Inst) MatchRunePos 1.3

func (i *Inst) MatchRunePos(r rune) int

MatchRunePos检查指令是否匹配(并使用)r. 如果是这样,则MatchRunePos返回匹配的符文对的索引(或者,当len(i.Rune)== 1时,符文单例). 如果不是,则MatchRunePos返回-1. 仅当i.Op == InstRune时才调用MatchRunePos.

func (*Inst) String

func (i *Inst) String() string

type InstOp

InstOp是指令操作码.

type InstOp uint8
const (
    InstAlt InstOp = iota
    InstAltMatch
    InstCapture
    InstEmptyWidth
    InstMatch
    InstFail
    InstNop
    InstRune
    InstRune1
    InstRuneAny
    InstRuneAnyNotNL
)

func (InstOp) String 1.3

func (i InstOp) String() string

type Op

Op是单个正则表达式运算符.

type Op uint8
const (
    OpNoMatch        Op = 1 + iota // matches no strings
    OpEmptyMatch                   // matches empty string
    OpLiteral                      // matches Runes sequence
    OpCharClass                    // matches Runes interpreted as range pair list
    OpAnyCharNotNL                 // matches any character except newline
    OpAnyChar                      // matches any character
    OpBeginLine                    // matches empty string at beginning of line
    OpEndLine                      // matches empty string at end of line
    OpBeginText                    // matches empty string at beginning of text
    OpEndText                      // matches empty string at end of text
    OpWordBoundary                 // matches word boundary `\b`
    OpNoWordBoundary               // matches word non-boundary `\B`
    OpCapture                      // capturing subexpression with index Cap, optional name Name
    OpStar                         // matches Sub[0] zero or more times
    OpPlus                         // matches Sub[0] one or more times
    OpQuest                        // matches Sub[0] zero or one times
    OpRepeat                       // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit)
    OpConcat                       // matches concatenation of Subs
    OpAlternate                    // matches alternation of Subs
)

func (Op) String 1.11

func (i Op) String() string

type Prog

Prog是已编译的正则表达式程序.

type Prog struct {
    Inst   []Inst
    Start  int // index of start instruction
    NumCap int // number of InstCapture insts in re
}

func Compile

func Compile(re *Regexp) (*Prog, error)

编译将正则表达式编译为要执行的程序. regexp应该已经被简化了(从re.Simplify返回).

func (*Prog) Prefix

func (p *Prog) Prefix() (prefix string, complete bool)

前缀返回一个文字字符串,该字符串必须与regexp的所有匹配项开始. 如果前缀是整个匹配项,则Complete为true.

func (*Prog) StartCond

func (p *Prog) StartCond() EmptyOp

StartCond返回任何匹配项中必须为true的前导空白宽度条件. 如果没有匹配项,则返回^ EmptyOp(0).

func (*Prog) String

func (p *Prog) String() string

type Regexp

Regexp是正则表达式语法树中的一个节点.

type Regexp struct {
    Op       Op // operator
    Flags    Flags
    Sub      []*Regexp  // subexpressions, if any
    Sub0     [1]*Regexp // storage for short Sub
    Rune     []rune     // matched runes, for OpLiteral, OpCharClass
    Rune0    [2]rune    // storage for short Rune
    Min, Max int        // min, max for OpRepeat
    Cap      int        // capturing index, for OpCapture
    Name     string     // capturing name, for OpCapture
}

func Parse

func Parse(s string, flags Flags) (*Regexp, error)

Parse解析由指定的Flags控制的正则表达式字符串s,并返回正则表达式解析树. 语法在顶级注释中描述.

func (*Regexp) CapNames

func (re *Regexp) CapNames() []string

CapNames沿着正则表达式查找捕获组的名称.

func (*Regexp) Equal

func (x *Regexp) Equal(y *Regexp) bool

相等报告x和y是否具有相同的结构.

func (*Regexp) MaxCap

func (re *Regexp) MaxCap() int

MaxCap使用正则表达式查找最大捕获索引.

func (*Regexp) Simplify

func (re *Regexp) Simplify() *Regexp

Simplify返回与re等效的正则表达式,但不计算重复次数,并具有其他各种简化形式,例如将/(?: a +)+ /重写为/ a + /. 生成的正则表达式将正确执行,但是其字符串表示形式将不会产生相同的解析树,因为捕获括号可能已被复制或删除. 例如,/(x){1,2} /的简化形式为/(x)(x)?/,但是两个括号都捕获为$ 1. 返回的正则表达式可以与原始结构共享或为原始结构.

func (*Regexp) String

func (re *Regexp) String() string

by  ICOPY.SITE