How to extract value from matched string with regexp

7,285 views
Skip to first unread message

Nguyên Nguyễn Văn Cao

unread,
Oct 3, 2012, 12:11:45 PM10/3/12
to golan...@googlegroups.com
For example I have:

reg := regexp.MustCompile("/user/[0-9]+/edit$")

and a string: "/user/999/edit".

How can I extract "999" part to a variable?

Larry Clapp

unread,
Oct 3, 2012, 12:26:11 PM10/3/12
to golan...@googlegroups.com
func main() {
s := "/user/999/edit"

// ... verify match with regex ...

// extract digits
n := strings.SplitN(s, "/", 4)[2]
fmt.Println(n)
// or
n = s[6 : 6+strings.Index(s[6:], "/")]
fmt.Println(n)
}


-- L

minux

unread,
Oct 3, 2012, 12:42:34 PM10/3/12
to Nguyên Nguyễn Văn Cao, golan...@googlegroups.com
package main

import (
"fmt"
"regexp"
)

func main() {
s := "/user/999/edit"
re := regexp.MustCompile(`/user/([0-9]+)/edit$`)
fmt.Println(re.FindStringSubmatch(s))
}


Reply all
Reply to author
Forward
0 new messages