使用 Golang 正则表达式查找一个整数后跟一个字符串

我想找到一个后跟术语“价格:”的整数,无论是在输出中,我只需要打印必须排除术语“价格:”的整数。现在,我的代码是这样的,输出是 [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))


肥皂起泡泡
浏览 192回答 2
2回答

眼眸繁星

您可以在数字模式周围使用捕获组并调用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!")    }} 请注意,这`Price:\s*(\d+)`是一个原始字符串文字,您不必额外转义形成正则表达式转义的反斜杠,因此\s*匹配零个或多个空格并(\d+)匹配并将 1+ 位数字捕获到此模式字符串文字中的第 1 组中。

吃鸡游戏

尝试使用下一个正则表达式:re := regexp.MustCompile(`Price:[[:space:]]([0-9]+)`) matches := re.FindStringSubmatch(str)唯一的区别 - 是括号[0-9],现在您可以通过以下方式访问 100 matches[1]:。您也可以替换:[[:space:]]with \s[0-9]with\d这样您的正则表达式看起来会更简单,例如:Price:\s(\d+)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go