Reputation: 37
I have a string:
s := "root 1 12345 /root/pathtomyfolder/jdk/jdk.1.8.0.25 org.catalina.startup"
I need to grep the version number to a string
Tried,
var re = regexp.MustCompile(`jdk.*`)
func main() {
matches := re.FindStringSubmatch(s)
fmt.Printf ("%q", matches)
}
Upvotes: 0
Views: 6417
Reputation: 3
if you need the value in a string variable to be used / manipulated elsewhere, you could add the following in the given example Marc gave:
a := fmt.Sprintf("%s", matches[1])
Upvotes: 0
Reputation: 21035
You need to specify capturing groups to extract submatches, as described in the package overview:
If 'Submatch' is present, the return value is a slice identifying the successive submatches of the expression. Submatches are matches of parenthesized subexpressions (also known as capturing groups) within the regular expression, numbered from left to right in order of opening parenthesis. Submatch 0 is the match of the entire expression, submatch 1 the match of the first parenthesized subexpression, and so on.
Something along the lines of the following:
func main() {
var re = regexp.MustCompile(`jdk\.([^ ]+)`)
s := "root 1 12345 /root/pathtomyfolder/jdk/jdk.1.8.0.25 org.catalina.startup"
matches := re.FindStringSubmatch(s)
fmt.Printf("%s", matches[1])
// Prints: 1.8.0.25
}
You'll of course want to check whether there actually is a submatch, or matches[1]
will panic.
Upvotes: 3