Golang : Customize scanner.Scanner to treat dash as part of identifier
Putting this down here for my own future reference. Ok, the problem that I'm solving today involved using the text/scanner
package to parse a given input with strings such as beli-belah
, buah-buahan
and jalan-jalan
.
The initial problem is that scanner.Scanner
will break buah-buahan
to buah
and buahan
.
So, how to customize the scanner to treat -
dash as part of the identifier?
Simple, use .IsIdentRune
method to override the default behavior of the scanner
.
For example,
var scn scanner.Scanner
scn.Init(rumiReader)
scn.Whitespace ^= 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' ' // don't skip tabs and new lines
// treat leading '-' as part of an identifier ... for word such as buah-buahan, biri-biri
scn.IsIdentRune = func(ch rune, i int) bool {
return ch == '-' && i == 0 || unicode.IsLetter(ch) || unicode.IsDigit(ch) && i > 0 || unicode.IsPunct(ch)
}
If you encounter the same problem as I am, hope this helps!
Reference :
See also : Golang : How to tokenize source code with text/scanner package?
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
+5.3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+5.1k Unix/Linux/MacOSx : How to remove an environment variable ?
+13.6k Golang : How to check if a file is hidden?
+27.1k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+7.5k Golang : Generate human readable password
+4.5k Linux/MacOSX : How to symlink a file?
+19.1k Golang : Get current URL example
+19.2k Golang : How to count the number of repeated characters in a string?
+26k Golang : Calculate future date with time.Add() function
+10k Golang : cannot assign type int to value (type uint8) in range error
+9k Golang : How to control fmt or log print format?
+10.3k Golang : Resolve domain name to IP4 and IP6 addresses.