Spec-Zone.ru › Go

Пакет syntax

  • import "regexp/syntax"
  • Обзор
  • Указатель

Обзор

Пакет syntax разбирает регулярные выражения в деревья разбора и компилирует деревья разбора в программы. Большинство пользователей регулярных выражений будут использовать средства пакета 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.CategoryAliases и unicode.Scripts.

Указатель

  • 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
  • func (i Op) String() string
  • 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 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_].

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

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 )"
    ErrNestingDepth          ErrorCode = "expression nests too deeply"
    ErrLarge                 ErrorCode = "expression too large"
)

func (ErrorCode) String

func (e ErrorCode) String() string

type Flags

Флаги управляют поведением анализатора и содержат информацию о контексте регулярного выражения.

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. Функцию MatchRunePos следует вызывать только при i.Op == InstRune.

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)

Compile компилирует регулярное выражение в исполняемую программу. Регулярное выражение уже должно быть упрощено (возвращено из re.Simplify).

func (*Prog) Prefix

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

Prefix возвращает буквальную строку, с которой должны начинаться все совпадения регулярного выражения. Complete имеет значение true, если префикс является всем совпадением.

func (*Prog) StartCond

func (p *Prog) StartCond() EmptyOp

StartCond возвращает начальные условия нулевой ширины, которые должны выполняться для любого совпадения. Возвращает ^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 разбирает строку регулярного выражения s с учётом заданных флагов и возвращает дерево разбора регулярного выражения. Синтаксис описан в комментарии в начале пакета.

func (*Regexp) CapNames

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

CapNames обходит регулярное выражение и находит имена захватывающих групп.

func (*Regexp) Equal

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

Equal сообщает, имеют ли 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

© Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
http://golang.org/pkg/regexp/syntax/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API