Regex is returning wrong results

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?

Your regex asks for "start with an a, have some random character, end with a b". So it will only ever match on strings that are exactly 3 chars long. You probably want to use .+ or .*, depending on the exact requirements.

Here you are asking again for a single character enclosed in spaces. You probably again want to use the + or * quantifiers for the .. And in this case you also want to be very careful about greediness or not. And even if you where using ^card\s.*\s(?P<Day>\d{2}), it will not give you the result you expect! Yes, in your particular examply the match would be 20, but its not the 20 you think it was!

Just check it out here:

1 Like