Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an integer followed by a string with Golang regexp

Tags:

regex

go

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))
} 
like image 280
Amid Avatar asked Aug 16 '18 10:08

Amid


2 Answers

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.

like image 138
Wiktor Stribiżew Avatar answered Nov 18 '22 20:11

Wiktor Stribiżew


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+)

like image 42
cn007b Avatar answered Nov 18 '22 18:11

cn007b