Golang : How to tokenize source code with text/scanner package?
It has been a while since I touch the topic on tokenizer.....err... since the day I actually built a compiler back in the 90's in Ada95!
Ok, time to cut the grandma or grandpa story.
This short code example below demonstrate how to tokenize souce code with Golang's text/scanner
package.
Here you go !
package main
import (
"fmt"
"strings"
"text/scanner"
)
func main() {
code := `<?php
echo "Hello World!";
?>`
codeReader := strings.NewReader(code)
fmt.Println(code)
fmt.Println("------------------------------")
fmt.Println("TOKENS : ")
fmt.Println("------------------------------")
var scn scanner.Scanner
scn.Init(codeReader)
tok := scn.Scan()
fmt.Println(scn.TokenText())
for tok != scanner.EOF {
tok = scn.Scan()
fmt.Println(scn.TokenText())
}
}
Play at : http://play.golang.org/p/R9pDAt2jOO
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.5k Golang : Totalize or add-up an array or slice example
+19.5k Golang : How to Set or Add Header http.ResponseWriter?
+9.3k Golang : How to protect your source code from client, hosting company or hacker?
+14.9k Golang : How to check for empty array string or string?
+5k Golang : Display packages names during compilation
+14.2k Golang : Fix image: unknown format error
+4.7k Adding Skype actions such as call and chat into web page examples
+6.6k Golang : How to determine if request or crawl is from Google robots
+13.9k Golang : Get dimension(width and height) of image file
+6.1k Java : Human readable password generator
+36.7k Golang : Display float in 2 decimal points and rounding up or down