Пакет синтаксиса
Обзор
Пакет синтаксиса парсит регулярные выражения в деревья разбора и компилирует деревья разбора в программы. Большинство клиентов регулярных выражений будут использовать средства пакета regexp (такие как regexp.Compile и regexp.Match) вместо этого пакета.
Синтаксис
Синтаксис регулярных выражений, понимаемый этим пакетом при разборе с флагом 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) (?<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 \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])
Классы символов Unicode — это те, что в unicode.Categories и unicode.Scripts.
Индекс
Файлы пакета
compile.go doc.go op_string.go parse.go perl_groups.go prog.go regexp.go simplify.go
func IsWordChar
func IsWordChar(r rune) bool
IsWordChar сообщает, является ли r «символом слова» во время оценки утверждений нулевой ширины \b и \B. Эти утверждения — только ASCII: символы слова — [A-Za-z0-9_].
тип 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 указывает, что позиция находится в конце текста.
тип Error
Error описывает ошибку при разборе регулярного выражения и указывает нарушающее выражение.
type Error struct {
Code ErrorCode
Expr string
}
func (*Error) Error
func (e *Error) Error() string
тип 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 )"
ErrNestingDepth ErrorCode = "expression nests too deeply"
ErrLarge ErrorCode = "expression too large"
) func (ErrorCode) String
func (e ErrorCode) String() string
тип Flags
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
) тип 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 сообщает, соответствует ли инструкция пустой строке между рунами before и after. Она должна вызываться только тогда, когда 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. MatchRunePos должен вызываться только тогда, когда i.Op == InstRune.
func (*Inst) String
func (i *Inst) String() string
тип 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
тип 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
тип 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)
Compile компилирует regexp в программу для выполнения. regexp должен быть уже упрощён (возвращён из re.Simplify).
func (*Prog) Prefix
func (p *Prog) Prefix() (prefix string, complete bool)
Prefix возвращает литеральную строку, с которой должны начинаться все совпадения для regexp. Complete — true, если префикс — это всё совпадение.
func (*Prog) StartCond
func (p *Prog) StartCond() EmptyOp
StartCond возвращает ведущие условия нулевой ширины, которые должны быть истинными в любом совпадении. Возвращает ^EmptyOp(0), если совпадения невозможны.
func (*Prog) String
func (p *Prog) String() string
тип 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 парсит строку регулярного выражения s, контролируемую указанными Flags, и возвращает дерево разбора регулярного выражения. Синтаксис описан в комментарии на самом верхнем уровне.
func (*Regexp) CapNames
func (re *Regexp) CapNames() []string
CapNames проходит по regexp, чтобы найти имена захватывающих групп.
func (*Regexp) Equal
func (x *Regexp) Equal(y *Regexp) bool
Equal сообщает, имеют ли x и y одинаковую структуру.
func (*Regexp) MaxCap
func (re *Regexp) MaxCap() int
MaxCap проходит по regexp, чтобы найти максимальный индекс захвата.
func (*Regexp) Simplify
func (re *Regexp) Simplify() *Regexp
Simplify возвращает regexp, эквивалентный re, но без подсчитанных повторений и с различными другими упрощениями, например, преобразованием /(?:a+)+/ в /a+/. Результирующий regexp будет выполняться правильно, но его строковое представление не создаст то же дерево разбора, потому что захватывающие скобки могут быть дублированы или удалены. Например, упрощённая форма /(x){1,2}/ — /(x)(x)?/, но обе скобки захватывают как $1. Возвращаемый regexp может совместно использовать структуру с оригиналом или быть оригиналом.
func (*Regexp) String
func (re *Regexp) String() string
© Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
http://golang.org/pkg/regexp/syntax/