I’ve the below code:
package main
import (
"fmt"
"regexp"
)
func main() {
// First part
s := "Never say never."
r := regexp.MustCompile(`(?i)^n`) // Do we have an 'N' or 'n' at the beginning?
fmt.Printf("%v", r.MatchString(s)) // true, case insensitive, correct answer
fmt.Println()
// Second part
r = regexp.MustCompile(`^a.b$`)
matched := r.MatchString("aaxbb")
fmt.Println(matched) // false, why?
fmt.Println()
// Third part
re := regexp.MustCompile(`.(?P<Day>\d{2})`)
matches := re.FindStringSubmatch("Some random date: 2001-01-20")
dayIndex := re.SubexpIndex("Day")
fmt.Println(matches[dayIndex]) // 20, correct answer
fmt.Println()
// Fourth part
re = regexp.MustCompile(`^card\s.\s(?P<Day>\d{2})`)
matches = re.FindStringSubmatch("card Some random date: 2001-01-20")
dayIndex := re.SubexpIndex("Day")
fmt.Println(matches[yearIndex]) // panic: runtime error: index out of range [1] with length 0, why?
}
First and Third parts are ok, and returning correct answers.
Second and Fourth parts are wrong and returns either wrong answers or errors, though they are almost same as parts 1 and 3 but with slight tuning?