Golang : 自定义 scanner.Scanner将破折号视为标识符的一部分

242 阅读1分钟

把这个写下来,供我自己将来参考。好的,我今天要解决的问题涉及到使用text/scanner 包来解析一个给定的输入字符串,如beli-belah,buah-buahanjalan-jalan

最初的问题是,scanner.Scanner 会将buah-buahan 破解为buahbuahan

那么,如何定制扫描器,将- 破折号作为标识符的一部分?

很简单,使用.IsIdentRune 方法来覆盖scanner 的默认行为。

比如说:


  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)
  }

如果你遇到了和我一样的问题,希望这对你有帮助!

参考:

golang.org/pkg/text/sc…