非常教程

Go参考手册

正则表达式 | regexp

regexp/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

正则表达式 | regexp相关

Go

Go 是一种编译型语言,它结合了解释型语言的游刃有余,动态类型语言的开发效率,以及静态类型的安全性。它也打算成为现代的,支持网络与多核计算的语言。要满足这些目标,需要解决一些语言上的问题:一个富有表达能力但轻量级的类型系统,并发与垃圾回收机制,严格的依赖规范等等。这些无法通过库或工具解决好,因此Go也就应运而生了。

主页 https://golang.org/
源码 https://go.googlesource.com/go
发布版本 1.9.2

Go目录

1.档案 | archive
2.缓冲区 | bufio
3.内置 | builtin
4.字节 | bytes
5.压缩 | compress
6.容器 | container
7.上下文 | context
8.加密 | crypto
9.数据库 | database
10.调试 | debug
11.编码 | encoding
12.错误 | errors
13. expvar
14.flag
15. fmt
16. go
17.散列 | hash
18.html
19.图像 | image
20.索引 | index
21.io
22.日志 | log
23.数学 | math
24. math/big
25.math/bits
26.math/cmplx
27.math/rand
28.拟态 | mime
29.net
30.net/http
31. net/mail
32. net/rpc
33.net/smtp
34. net/textproto
35. net/url
36.os
37.路径 | path
38.插件 | plugin
39.反射 | reflect
40.正则表达式 | regexp
41.运行时 | runtime
42.排序算法 | sort
43.转换 | strconv
44.字符串 | strings
45.同步 | sync
46.系统调用 | syscall
47.测试 | testing
48.文本 | text
49.时间戳 | time
50.unicode
51.不安全性 | unsafe
52.Go 语言数据类型
53.Go 语言基础语法
54.Go 语言结构
55.Go 语言 select 语句
56.Go 语言 switch 语句
57.Go 语言 if 语句嵌套
58.Go 语言 if…else 语句
59.Go 语言 if 语句
60.Go 语言运算符
61.Go 语言常量
62.Go 语言函数闭包
63.Go 语言函数作为实参
64.Go 语言函数引用传递值
65.Go 语言函数值传递值
66.Go 语言函数
67.Go 语言 goto 语句
68.Go 语言 continue 语句
69.Go 语言 break 语句
70.Go 语言循环嵌套
71.Go 语言 for 循环
72.Go 语言结构体
73.Go 语言指针作为函数参数
74.Go 语言指向指针的指针
75.Go 语言指针数组
76.Go 语言指针
77.Go 语言向函数传递数组
78.Go 语言多维数组
79.Go 语言变量作用域
80.Go 语言函数方法
81.Go 错误处理
82.Go 语言接口
83.Go 语言类型转换
84.Go 语言递归函数
85.Go 语言Map(集合)
86.Go 语言范围(Range)
87.Go 语言切片(Slice)
88.Go 并发
89.Go fmt.Sprintf 格式化字符串