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

5
我想找到一个紧跟着“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))
} 

你说你想找到一个跟在“价格”后面的整数,但你的示例只显示了一个在“价格”之前的数字。 - Jonathan Hall
2个回答

6

您可以使用数字模式周围的捕获组,并调用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组。

2

尝试使用以下正则表达式:

re := regexp.MustCompile(`Price:[[:space:]]([0-9]+)`)
matches := re.FindStringSubmatch(str)

唯一的区别在于括号中有[0-9],现在您可以通过matches[1]访问100。
此外,您可以替换:
[[:space:]]\s
[0-9]\d
这样您的正则表达式看起来更简单,如:Price:\s(\d+)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接