Created
April 30, 2016 09:11
-
-
Save catatsuy/97ded7e1c99eec52be7ae142d6095462 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"regexp" | |
) | |
var digitRegexp = regexp.MustCompile("[0-9]+") | |
// cf: https://blog.golang.org/go-slices-usage-and-internals | |
// re-sliceはコピーをしないので、この関数の返値が不要になるまでbはGCされない | |
func FindDigits(filename string) []byte { | |
b, _ := ioutil.ReadFile(filename) | |
return digitRegexp.Find(b) | |
} | |
// copyを使うとbがGCできるようにする | |
func CopyDigits(filename string) []byte { | |
b, _ := ioutil.ReadFile(filename) | |
b = digitRegexp.Find(b) | |
c := make([]byte, len(b)) | |
copy(c, b) | |
return c | |
} | |
// appendを使うと簡潔にできる | |
func AppendDigits(filename string) []byte { | |
b, _ := ioutil.ReadFile(filename) | |
b = digitRegexp.Find(b) | |
c := make([]byte, 0, len(b)) | |
c = append(c, b...) | |
return c | |
} | |
func main() { | |
fmt.Println(string(FindDigits("tmp.txt"))) | |
fmt.Println(string(CopyDigits("tmp.txt"))) | |
fmt.Println(string(AppendDigits("tmp.txt"))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment