0

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)
}
1
  • Welcome to Stack Overflow! "Please help" isn't much of a question. You should show what you have tried, and what didn't work. Please include a Minimal, Complete, and Verifiable example. You probably want to look at regexp for this. Commented Jan 7, 2018 at 14:21

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I need to get the version details in a string. Not able to get that
matches[1] in my answer is a string containing 1.8.0.25. As far as I can tell, this is exactly what you need.
Might want to try it out on regex-golang.appspot.com/assets/html/index.html to see the result?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.