forked from chonla/format
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfmt.go
More file actions
54 lines (44 loc) · 1.06 KB
/
fmt.go
File metadata and controls
54 lines (44 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package format
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile(`%\(([a-zA-Z0-9_]+)\)[.0-9]*[xsvTtbcdoqXxUeEfFgGp]`)
// Printf support named format
func Printf(format string, params map[string]interface{}) {
f, p := parse(format, params)
fmt.Printf(f, p...)
}
// Sprintf support named format
func Sprintf(format string, params map[string]interface{}) string {
f, p := parse(format, params)
return fmt.Sprintf(f, p...)
}
func parse(format string, params map[string]interface{}) (string, []interface{}) {
f, n := reformat(format)
var p []interface{}
for _, v := range n {
p = append(p, params[v])
}
return f, p
}
func reformat(f string) (string, []string) {
m := re.FindAllStringSubmatch(f, -1)
i := re.FindAllStringSubmatchIndex(f, -1)
ord := []string{}
for _, v := range m {
ord = append(ord, v[1])
}
pair := []int{0}
for _, v := range i {
pair = append(pair, v[2]-1)
pair = append(pair, v[3]+1)
}
pair = append(pair, len(f))
plen := len(pair)
out := ""
for n := 0; n < plen; n += 2 {
out += f[pair[n]:pair[n+1]]
}
return out, ord
}