本文整理汇总了Golang中regexp.Regexp.SubexpNames方法的典型用法代码示例。如果您正苦于以下问题:Golang Regexp.SubexpNames方法的具体用法?Golang Regexp.SubexpNames怎么用?Golang Regexp.SubexpNames使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类regexp.Regexp
的用法示例。
在下文中一共展示了Regexp.SubexpNames方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: logFilenameToTime
func logFilenameToTime(filename string, filenameToTimeRegex *regexp.Regexp) (time.Time, error) {
if filenameToTimeRegex == nil {
return time.Now(), fmt.Errorf("filename_to_time_regex is not set in indexer configuration")
}
n1 := filenameToTimeRegex.SubexpNames()
r2s := filenameToTimeRegex.FindAllStringSubmatch(filename, -1)
if len(r2s) == 0 {
return time.Now(), fmt.Errorf("filename_to_time_regex did not match %q", filename)
}
r2 := r2s[0]
md := map[string]string{}
for i, n := range r2 {
md[n1[i]] = n
}
getOrZero := func(key string) int {
val, exists := md[key]
if !exists {
return 0
}
num, err := strconv.Atoi(val)
if err != nil {
return 0
}
return num
}
year := getOrZero("year")
month := time.Month(getOrZero("month"))
day := getOrZero("day")
hour := getOrZero("hour")
minute := getOrZero("minute")
return time.Date(year, month, day, hour, minute, 0, 0, time.UTC), nil
}
示例2: compilePattern
func compilePattern(pattern string) (*regexp.Regexp, error) {
var (
re *regexp.Regexp
err error
)
// Compile regexp pattern
if re, err = regexp.Compile(pattern); err != nil {
return nil, err
}
// Validate pattern keywords
groups := make(map[string]bool)
for _, key := range re.SubexpNames() {
if key == "" {
continue
} else if key == "source" || key == "metric" {
groups[key] = true
} else {
return nil, fmt.Errorf("invalid pattern keyword `%s'", key)
}
}
if !groups["source"] {
return nil, fmt.Errorf("missing pattern keyword `source'")
} else if !groups["metric"] {
return nil, fmt.Errorf("missing pattern keyword `metric'")
}
return re, nil
}
示例3: Route
// add route
func (mvc *MvcFilter) Route(name string, pattern string, method string, controller interface{}) error {
if pattern == "" {
return NewHttpError("gomvc invalid pattern " + pattern)
}
if controller == nil {
return NewHttpError("gomvc invalid controller ")
}
var r *regexp.Regexp
var err error
if r, err = regexp.Compile(pattern); err != nil {
return err
}
route := Route{Name: name, Pattern: pattern, Method: method}
route.reg = r
route.names = r.SubexpNames()[1:]
if fv, ok := controller.(reflect.Value); ok {
route.Controller = fv
} else {
route.Controller = reflect.ValueOf(controller)
}
mvc.Routes = append(mvc.Routes, route)
return nil
}
示例4: RegexpFilter
func RegexpFilter(filterReg *regexp.Regexp, data []byte) (outdata []byte) {
if nil == filterReg {
return data
}
matches := filterReg.FindAllSubmatch(data, -1)
if nil == matches {
log.Printf("[ERROR] failed to match filter regex, pattern %s did not match", filterReg.String())
if *gDebug {
log.Println("======= debug: target data =======")
log.Println(string(data))
log.Println("==============")
}
return nil
}
for _, match := range matches {
for patInd, patName := range filterReg.SubexpNames() {
switch patName {
case PATTERN_FILTER:
outdata = append(outdata, match[patInd]...)
}
}
}
if *gDebug {
log.Println("======= debug: filter regex ========")
log.Println(filterReg.String())
log.Println("======= debug: filtered data =======")
log.Println(string(outdata))
log.Println("==============")
}
return
}
示例5: ParseDatabaseDSN
func ParseDatabaseDSN(urlRegexp *regexp.Regexp, url string) DatabaseDSN {
defer func() {
_ = recover()
}()
dsn := DatabaseDSN{}
match := urlRegexp.FindStringSubmatch(url)
for i, name := range urlRegexp.SubexpNames() {
if i != 0 {
if name == "host" {
dsn.Host = match[i]
}
if name == "port" {
dsn.Port = match[i]
}
if name == "user" {
dsn.User = match[i]
}
if name == "password" {
dsn.Password = match[i]
}
if name == "name" {
dsn.Name = match[i]
}
}
}
return dsn
}
示例6: ServeHTTP
// ServeHTTP parses the path parameters, calls SetPathParameters of
// the corresponding hander, then directs traffic to it.
func (r *RouteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
glog.Infof("%s: '%s'", req.Method, req.URL.String())
pathstr := req.URL.Path[len(r.path):]
var match []string
var pattern *regexp.Regexp
var handler Handler
for e := r.patternHandlers.Front(); e != nil; e = e.Next() {
h := e.Value.(*patternHandler)
pattern = h.Regexp
handler = h.Handler
match = pattern.FindStringSubmatch(pathstr)
if match != nil {
break
}
}
if match == nil {
glog.Warningf("Cannot find a matching pattern for Path `%s'",
pathstr)
http.NotFound(w, req)
return
}
kvpairs := make(map[string]string)
for i, name := range pattern.SubexpNames() {
// ignore full match and unnamed submatch
if i == 0 || name == "" {
continue
}
kvpairs[name] = match[i]
}
glog.V(1).Infof("Parsed path parameters: %s", kvpairs)
handler.ServeHTTP(w, req, kvpairs)
}
示例7: NamedUrlValuesRegexpGroup
// match regexp with string, and return a named group map
// Example:
// regexp: "(?P<name>[A-Za-z]+)-(?P<age>\\d+)"
// string: "CGC-30"
// return: map[string][]string{ "name":["CGC"], "age":["30"] }
func NamedUrlValuesRegexpGroup(str string, reg *regexp.Regexp) (ng url.Values, matched bool) {
rst := reg.FindStringSubmatch(str)
if len(rst) < 1 {
return
}
//for i,s :=range rst{
// fmt.Printf("%d => %s\n",i,s)
//}
ng = url.Values{}
lenRst := len(rst)
sn := reg.SubexpNames()
for k, v := range sn {
// SubexpNames contain the none named group,
// so must filter v == ""
//fmt.Printf("%s => %s\n",k,v)
if k == 0 || v == "" {
continue
}
if k+1 > lenRst {
break
}
ng.Add(v, rst[k])
}
matched = true
return
}
示例8: FromString
func FromString(dur string) (*Duration, error) {
var (
match []string
re *regexp.Regexp
)
if week.MatchString(dur) {
match = week.FindStringSubmatch(dur)
re = week
} else if full.MatchString(dur) {
match = full.FindStringSubmatch(dur)
re = full
} else {
return nil, ErrBadFormat
}
d := &Duration{}
for i, name := range re.SubexpNames() {
part := match[i]
if i == 0 || name == "" || part == "" {
continue
}
val, err := strconv.Atoi(part)
if err != nil {
return nil, err
}
// Check that no component is explicitly 0,
// e.g. PT60M0S
if val == 0 {
return nil, fmt.Errorf("%s cannot be 0", name)
}
switch name {
case "year":
d.Years = val
case "month":
return nil, ErrNoMonth
case "week":
d.Weeks = val
case "day":
d.Days = val
case "hour":
d.Hours = val
case "minute":
d.Minutes = val
case "second":
d.Seconds = val
default:
return nil, errors.New(fmt.Sprintf("unknown field %s", name))
}
}
return d, nil
}
示例9: URESearch
func URESearch(pattern *regexp.Regexp, content string) map[string]string {
matches := pattern.FindStringSubmatch(content)
result := make(map[string]string)
for i, name := range pattern.SubexpNames() {
result[name] = matches[i]
}
return result
}
示例10: ParsePubDate
func ParsePubDate(formatReg *regexp.Regexp, dateStr string) (time.Time, error) {
if nil == formatReg {
log.Printf("[ERROR] error parsing pubdate, date format regexp is nil")
return time.Time{}, errors.New("date format regexp is nil")
}
pubdateStr := strings.TrimSpace(dateStr)
if "" == pubdateStr {
log.Printf("[ERROR] error parsing pubdate, pubdate string is empty")
return time.Time{}, errors.New("pubdate string is empty")
}
now := time.Now()
year := now.Year()
month := int(now.Month())
day := now.Day()
hour := now.Hour()
minute := now.Minute()
second := now.Second()
match := formatReg.FindSubmatch([]byte(pubdateStr))
if nil == match {
log.Printf("[ERROR] error parsing pubdate %s, pattern %s match failed", pubdateStr, formatReg.String())
return time.Time{}, errors.New("failed to match pubdate pattern")
}
for patInd, patName := range formatReg.SubexpNames() {
var err error
patVal := string(match[patInd])
switch patName {
case PATTERN_YEAR:
year, err = strconv.Atoi(patVal)
case PATTERN_MONTH:
month, err = ParseDateMonth(patVal)
case PATTERN_DAY:
day, err = strconv.Atoi(patVal)
case PATTERN_HOUR:
hour, err = strconv.Atoi(patVal)
case PATTERN_MINUTE:
minute, err = strconv.Atoi(patVal)
case PATTERN_SECOND:
second, err = strconv.Atoi(patVal)
}
if nil != err {
log.Printf("[ERROR] error parsing pubdate: %s, time value %s cannot be parsed: %s",
pubdateStr,
match[patInd],
err,
)
return time.Time{}, err
}
}
return time.Date(year, time.Month(month), day, hour, minute, second, 0, GOFEED_DEFAULT_TIMEZONE), nil
}
示例11: decomposeTreadDumpLineRe
// Use the given regex to decompose a line of the thread dump into the matched fields
//regex groups start OMIT
func decomposeTreadDumpLineRe(threadDumpLine string, r *regexp.Regexp) (groups map[string]string, err error) {
matches := r.FindStringSubmatch(threadDumpLine)
names := r.SubexpNames()
groups = make(map[string]string)
for i, name := range names {
groups[name] = matches[i]
}
return
}
示例12: mapParams
func mapParams(regex *regexp.Regexp, matches []string) (p Params) {
for i, n := range regex.SubexpNames() {
if len(n) > 0 {
v := Param{}
v.Key = n
v.Value = matches[i]
p = append(p, v)
}
}
return
}
示例13: getMatchMap
// Transform our matches in a readable hash map.
//
// The resulting hash map will be something like { "Heap1": 123 }
func getMatchMap(re *regexp.Regexp, matches []string) map[string]string {
matchingNames := re.SubexpNames()[1:]
matchMap := map[string]string{}
for i, value := range matches[1:] {
if matchingNames[i] == "" {
continue
}
matchMap[matchingNames[i]] = value
}
return matchMap
}
示例14: getKeywordArguments
// getKeywordArguments is called by the base handler to extract keyword arguments from a URL pattern.
func getKeywordArguments(path string, pattern *regexp.Regexp) (args URLArgs) {
args = make(URLArgs)
matches := pattern.FindAllStringSubmatch(path, -1)
for i, key := range pattern.SubexpNames() {
if i == 0 || key == "" {
continue
}
args[key] = matches[0][i]
}
return args
}
示例15: SubexpNames
// SubexpNames returns a mapping of the sub-expression names to values if the Regexp
// successfully matches the string, otherwise, it returns false.
func SubexpNames(r *regexp.Regexp, s string) (bool, map[string]string) {
if matches := r.FindStringSubmatch(strings.TrimSpace(s)); matches != nil {
names := r.SubexpNames()
result := make(map[string]string)
for i, match := range matches {
result[names[i]] = strings.TrimSpace(match)
}
return true, result
}
return false, nil
}