使用 Golang regexp 查找一个整数后跟一个字符串

drd*_*rdn 5 regex go

我想找到一个整数,后面跟“Price:”这个词,无论是在输出中,我只需要打印必须排除“Price:”这个词的整数。现在,我的代码是这样的,输出是[Price: 100],但我只需要输出100。

package main 

import (
    "regexp"
    "fmt"
)

const str = "Some strings. Price: 100$. Some strings123"

func main() {
    re := regexp.MustCompile("Price:[[:space:]][0-9]+")
    fmt.Println(re.FindAllString(str, -1))
} 
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 5

您可以在数字模式周围使用捕获组并调用re.FindStringSubmatch

package main 

import (
    "regexp"
    "fmt"
)

const str = "Some strings. Price: 100$. Some strings123"

func main() {
    re := regexp.MustCompile(`Price:\s*(\d+)`)
    match := re.FindStringSubmatch(str)
    if match != nil {
        fmt.Println(match[1])
    } else {
        fmt.Println("No match!")
    }
} 
Run Code Online (Sandbox Code Playgroud)

请注意,这`Price:\s*(\d+)`是一个原始字符串文字,您不必额外转义形成正则表达式转义的反斜杠,因此\s*匹配零个或多个空格并将(\d+)1+ 位数字匹配并捕获到此模式字符串文字中的第 1 组。