regexp/syntax
syntax包
import "regexp/syntax"
- 概述
- 索引
概述
包语法将正则表达式解析为解析树并将解析树编译为程序。大多数正则表达式的客户端将使用regexp包的工具(如编译和匹配)而不是此包。
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
复合语句:
xy x followed by y
x|y x or y (prefer x)
重复:
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的最小或最大重复次数的表单。无限重复不受此限制。
分组:
(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(r rune) bool
- type EmptyOp
- func EmptyOpContext(r1, r2 rune) EmptyOp
- type Error
- func (e *Error) Error() string
- type ErrorCode
- func (e ErrorCode) String() string
- type Flags
- type Inst
- func (i *Inst) MatchEmptyWidth(before rune, after rune) bool
- func (i *Inst) MatchRune(r rune) bool
- func (i *Inst) MatchRunePos(r rune) int
- func (i *Inst) String() string
- type InstOp
- func (i InstOp) String() string
- type Op
- type Prog
- func Compile(re *Regexp) (*Prog, error)
- func (p *Prog) Prefix() (prefix string, complete bool)
- func (p *Prog) StartCond() EmptyOp
- func (p *Prog) String() string
- type Regexp
- func Parse(s string, flags Flags) (*Regexp, error)
- func (re *Regexp) CapNames() []string
- func (x *Regexp) Equal(y *Regexp) bool
- func (re *Regexp) MaxCap() int
- func (re *Regexp) Simplify() *Regexp
- func (re *Regexp) String() string
文件包
compile.go doc.go parse.go perl_groups.go prog.go regexp.go simplify.go
func IsWordCharSource
func IsWordChar(r rune) bool
IsWordChar在评估\ b和\ B在零宽度报告中r是否被认为是“单词字符”。这些断言仅为ASCII:单词字符为A-Za-z0-9_。
type EmptyOpSource
EmptyOp指定一种或多种零宽度断言的混合。
type EmptyOp uint8
const (
EmptyBeginLine EmptyOp = 1 << iota
EmptyEndLine
EmptyBeginText
EmptyEndText
EmptyWordBoundary
EmptyNoWordBoundary
)
func EmptyOpContextSource
func EmptyOpContext(r1, r2 rune) EmptyOp
EmptyOpContext返回在符号r1和r2之间的位置满足的零宽度断言。传递r1 == -1表示该位置在文本的开头。传递r2 == -1表示位置在文本的末尾。
type ErrorSource
错误描述了解析正则表达式失败并给出违规表达式。
type Error struct {
Code ErrorCode
Expr string
}
func (*Error) ErrorSource
func (e *Error) Error() string
type ErrorCodeSource
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) StringSource
func (e ErrorCode) String() string
type FlagsSource
标志控制解析器的行为并记录关于正则表达式上下文的信息。
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 InstSource
Inst是正则表达式程序中的单个指令。
type Inst struct {
Op InstOp
Out uint32 // all but InstMatch, InstFail
Arg uint32 // InstAlt, InstAltMatch, InstCapture, InstEmptyWidth
Rune []rune
}
func (*Inst) MatchEmptyWidthSource
func (i *Inst) MatchEmptyWidth(before rune, after rune) bool
MatchEmptyWidth报告指令是否匹配符文之前和之后的空字符串。只应在i.Op == InstEmptyWidth时调用它。
func (*Inst) MatchRuneSource
func (i *Inst) MatchRune(r rune) bool
MatchRune报告指令是否匹配(并消耗)r。它应该只在i.Op == InstRune时被调用。
func (*Inst) MatchRunePosSource
func (i *Inst) MatchRunePos(r rune) int
MatchRunePos检查指令是否匹配(并消耗)r。如果是这样,MatchRunePos返回匹配符文对的索引(或者,当len(i.Rune)== 1时,符文单例)。如果不是,则MatchRunePos返回-1。MatchRunePos只应在i.Op == InstRune时调用。
func (*Inst) StringSource
func (i *Inst) String() string
type InstOpSource
InstOp是一个指令操作码。
type InstOp uint8
const (
InstAlt InstOp = iota
InstAltMatch
InstCapture
InstEmptyWidth
InstMatch
InstFail
InstNop
InstRune
InstRune1
InstRuneAny
InstRuneAnyNotNL
)
func (InstOp) StringSource
func (i InstOp) String() string
type OpSource
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
)
type ProgSource
Prog是编译的正则表达式程序。
type Prog struct {
Inst []Inst
Start int // index of start instruction
NumCap int // number of InstCapture insts in re
}
func CompileSource
func Compile(re *Regexp) (*Prog, error)
编译将regexp编译成要执行的程序。正则表达式应该已经被简化了(从re.Simplify返回)。
func (*Prog) PrefixSource
func (p *Prog) Prefix() (prefix string, complete bool)
前缀返回所有匹配的正则表达式必须以字符串开头的文字字符串。如果前缀是整个匹配,则结果为真。
func (*Prog) StartCondSource
func (p *Prog) StartCond() EmptyOp
StartCond返回在任何匹配中必须为true的前导空白条件。如果不可能匹配,它返回^ EmptyOp(0)。
func (*Prog) StringSource
func (p *Prog) String() string
type RegexpSource
正则表达式是正则表达式语法树中的一个节点。
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 ParseSource
func Parse(s string, flags Flags) (*Regexp, error)
解析由指定标志控制的正则表达式字符串s,并返回正则表达式解析树。该语法在顶级注释中进行了描述。
func (*Regexp) CapNamesSource
func (re *Regexp) CapNames() []string
CapNames使用正则表达式查找捕获组的名称。
func (*Regexp) EqualSource
func (x *Regexp) Equal(y *Regexp) bool
如果x和y具有相同的结构,则相等返回true。
func (*Regexp) MaxCapSource
func (re *Regexp) MaxCap() int
MaxCap使用正则表达式查找最大捕获索引。
func (*Regexp) SimplifySource
func (re *Regexp) Simplify() *Regexp
简化返回相当于re的regexp,但不需要重复计算和其他各种简化,例如重写/(?: a +)+ / to / a + /。生成的正则表达式将正确执行,但其字符串表示形式不会生成相同的分析树,因为捕获的括号可能已被复制或删除。例如,/(x){1,2} /的简化形式是/(x)(x)?/但两个圆括号都捕获为$ 1。返回的正则表达式可能与原始结构共享或成为原始结构。
func (*Regexp) StringSource
func (re *Regexp) String() string