我想找到一個后跟術語“價格:”的整數,無論是在輸出中,我只需要打印必須排除術語“價格:”的整數。現在,我的代碼是這樣的,輸出是 [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))}
2 回答

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
您可以在數字模式周圍使用捕獲組并調用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 組中。

吃雞游戲
TA貢獻1829條經驗 獲得超7個贊
嘗試使用下一個正則表達式:
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+)
- 2 回答
- 0 關注
- 170 瀏覽
添加回答
舉報
0/150
提交
取消