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
+15.8k Golang : convert string or integer to big.Int type
+6.3k Golang : Check if password length meet the requirement
+6.4k Golang : How to setup a disk space used monitoring service with Telegram bot
+19.7k Android Studio : AlertDialog and EditText to get user string input example
+38.6k Golang : How to iterate over a []string(array)
+10k Golang : Generate random integer or float number
+33.5k Golang : Smarter Error Handling with strings.Contains()
+17.3k Golang : Simple client server example
+4.7k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+23.4k Golang : Use regular expression to validate domain name
+21.8k Golang : Repeat a character by multiple of x factor