34

go 正则的使用

 4 years ago
source link: https://www.tuicool.com/articles/Rr2qier
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

定义一个正则表达式

调用 regexp 下面的几个方法并传入一个正则的字符串形式的参数定义一个正则表达式

例如 : regexp.MustCompile("\d")

Compile
CompilePOSIX
MustCompile
MustCompilePOSIX

方法概述

regexp包中有16种方法来匹配正则表达式并标识匹配的文本,他们的名称可以使用这个正则来匹配

Find(All)?(String)?(Submatch)?(Index)?

如果存在 All 该函数将匹配整个表达式的连续非重叠匹配。方法返回的是一个包含非all 值得切片,这个方法使用一个额外的参数整数参数 n, 如果n> = 0,则该函数最多返回n个匹配项/子匹配项;否则,它返回所有匹配项/子匹配项。

如果存在 String 参数会是一个 string ,否则参数是一个 []byte 返回值也会相应的调整.

如果存在 Submatch 返回值是一个切片,用于标识表达式的连续子匹配项, 子匹配项是正则表达式中带括号的子表达式(也称为捕获组)的匹配项,按左括号的顺序从左到右编号。子匹配0是整个表达式的匹配项,子匹配1是第一个带括号的子表达式的匹配项,依此类推。

如果存在 Index , 则返回输入字符串匹配项和子匹配项字节索引对, result[2*n:2*n+1] 标识第n个子匹配项的索引, n==0 是整个表达式匹配的结果的索引对,如果不存在 Index ,则通过匹配/子匹配的文本识别匹配。

还有一些其他方法与此模式不匹配。

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile the expression once, usually at init time.
    // Use raw strings to avoid having to quote the backslashes.
    var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)

    fmt.Println(validID.MatchString("adam[23]"))
    fmt.Println(validID.MatchString("eve[7]"))
    fmt.Println(validID.MatchString("Job[48]"))
    fmt.Println(validID.MatchString("snakey"))
}

翻译自 go regexp

regex syntex 正则语法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK