Source file
src/text/scanner/example_test.go
1
2
3
4
5 package scanner_test
6
7 import (
8 "fmt"
9 "strings"
10 "text/scanner"
11 "unicode"
12 )
13
14 func Example() {
15 const src = `
16 // This is scanned code.
17 if a > 10 {
18 someParsable = text
19 }`
20
21 var s scanner.Scanner
22 s.Init(strings.NewReader(src))
23 s.Filename = "example"
24 for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
25 fmt.Printf("%s: %s\n", s.Position, s.TokenText())
26 }
27
28
29
30
31
32
33
34
35
36
37
38 }
39
40 func Example_isIdentRune() {
41 const src = "%var1 var2%"
42
43 var s scanner.Scanner
44 s.Init(strings.NewReader(src))
45 s.Filename = "default"
46
47 for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
48 fmt.Printf("%s: %s\n", s.Position, s.TokenText())
49 }
50
51 fmt.Println()
52 s.Init(strings.NewReader(src))
53 s.Filename = "percent"
54
55
56 s.IsIdentRune = func(ch rune, i int) bool {
57 return ch == '%' && i == 0 || unicode.IsLetter(ch) || unicode.IsDigit(ch) && i > 0
58 }
59
60 for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
61 fmt.Printf("%s: %s\n", s.Position, s.TokenText())
62 }
63
64
65
66
67
68
69
70
71
72
73 }
74
75 func Example_mode() {
76 const src = `
77 // Comment begins at column 5.
78
79 This line should not be included in the output.
80
81 /*
82 This multiline comment
83 should be extracted in
84 its entirety.
85 */
86 `
87
88 var s scanner.Scanner
89 s.Init(strings.NewReader(src))
90 s.Filename = "comments"
91 s.Mode ^= scanner.SkipComments
92
93 for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
94 txt := s.TokenText()
95 if strings.HasPrefix(txt, "//") || strings.HasPrefix(txt, "/*") {
96 fmt.Printf("%s: %s\n", s.Position, txt)
97 }
98 }
99
100
101
102
103
104
105
106
107 }
108
109 func Example_whitespace() {
110
111 const src = `aa ab ac ad
112 ba bb bc bd
113 ca cb cc cd
114 da db dc dd`
115
116 var (
117 col, row int
118 s scanner.Scanner
119 tsv [4][4]string
120 )
121 s.Init(strings.NewReader(src))
122 s.Whitespace ^= 1<<'\t' | 1<<'\n'
123
124 for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
125 switch tok {
126 case '\n':
127 row++
128 col = 0
129 case '\t':
130 col++
131 default:
132 tsv[row][col] = s.TokenText()
133 }
134 }
135
136 fmt.Print(tsv)
137
138
139
140 }
141
View as plain text