[英]Find an integer followed by a string with Golang regexp
我想找到一個整數,其后緊跟術語“ 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))
}
您可以在數字模式周圍使用捕獲組,然后調用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:]]
與\\s
[0-9]
與\\d
因此您的正則表達式看起來會更簡單,例如: Price:\\s(\\d+)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.