Golang Regexp Cheat Sheet

Code:

matched, _ := regexp.Match("abc", []byte("abcd"))
fmt.Println("abc in abcd:", matched)

matched, _ = regexp.Match("abd", []byte("abcd"))
fmt.Println("abd in abcd:", matched)

matched, _ = regexp.MatchString("a", "a")
fmt.Println("a in a:", matched)

if _, err := regexp.Compile("["); err != nil {
	fmt.Println("Error compiling regex:", err.Error())
}

func() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("MustCompile panic")
		}
	}()
	_ = regexp.MustCompile("[")
}()

Output:

abc in abcd: true
abd in abcd: false
a in a: true
Error compiling regex: error parsing regexp: missing closing ]: `[`
MustCompile panic

Code:

testPattern := regexp.MustCompile("(abc|def|g)")
foundBytes := testPattern.Find([]byte("abcdefg"))
fmt.Println("foundBytes:", string(foundBytes))

foundTwo := testPattern.FindAll([]byte("abcdefg"), -1)
for idx, found := range foundTwo {
	fmt.Println("foundTwo", idx+1, string(found))
}

searchBytes := []byte("abcdefg")
foundIndex := testPattern.FindIndex(searchBytes)
fmt.Println("foundIndex:", foundIndex)
fmt.Println("using Indices:", string(searchBytes[foundIndex[0]:foundIndex[1]]))
foundAllIndex := testPattern.FindAllIndex([]byte("abcdefg"), -1)
fmt.Println("foundAllIndex:", foundAllIndex)
for idx := range foundAllIndex {
	fmt.Println("foundAll", idx+1, string(searchBytes[foundAllIndex[idx][0]:foundAllIndex[idx][1]]))
}

foundTwo = testPattern.FindAll([]byte("abcdefg"), 2)
for idx, found := range foundTwo {
	fmt.Println("foundTwo", idx+1, string(found))
}

Output:

foundBytes: abc
foundIndex: [0 3]
using Indices: abc
foundAllIndex: [[0 3] [3 6] [6 7]]
foundAll 1 abc
foundAll 2 def
foundAll 3 g
foundTwo 1 abc
foundTwo 2 def
foundTwo 3 g
foundTwo 1 abc
foundTwo 2 def

Leave a Reply