简体   繁体   English

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

[英]Find an integer followed by a string with Golang regexp

I want to find an integer which is followed by the term "Price: ", whether in the output, I only need to print the integer which must be excluded the term "Price: ". 我想找到一个整数,其后紧跟术语“ Price:”,无论是否在输出中,我只需要打印必须排除术语“ Price:”的整数。 Right now, my code is like this and the output is [Price: 100], but I only need 100 in the output. 现在,我的代码是这样的,输出是[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))
} 

You may use a capturing group around the number pattern and call re.FindStringSubmatch : 您可以在数字模式周围使用捕获组,然后调用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!")
    }
} 

Note that `Price:\\s*(\\d+)` is a raw string literal where you do not have to extra-escape backslashes that form regex escapes, so \\s* matches zero or more whitespaces and (\\d+) matches and captures 1+ digits into Group 1 in this pattern string literal. 请注意, `Price:\\s*(\\d+)`是原始字符串文字,您无需额外转义形成正则表达式转义的反斜杠,因此\\s*匹配零个或多个空格,而(\\d+)匹配并捕获在此模式字符串文字中,第1组中的1+位数字。

Try to use next regexp: 尝试使用下一个正则表达式:

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

The only difference - is parentheses around [0-9] , now you can access 100 by: matches[1] . 唯一的区别-是[0-9]左右的括号,现在您可以通过以下方式访问100: matches[1]

Also you can replace: 您也可以替换:
[[:space:]] with \\s [[:space:]]\\s
[0-9] with \\d [0-9]\\d
so your regex will look simpler, like: Price:\\s(\\d+) 因此您的正则表达式看起来会更简单,例如: Price:\\s(\\d+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM