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: ". Right now, my code is like this and the output is [Price: 100], but I only need 100 in the output.
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
:
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.
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]
.
Also you can replace:
[[:space:]]
with \s
[0-9]
with \d
so your regex will look simpler, like: Price:\s(\d+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With