-3

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[dayIndex]) // 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?

blackgreen
  • 18,419
  • 19
  • 55
  • 71
Hasan A Yousef
  • 19,411
  • 21
  • 113
  • 174
  • There is a lot of explanation in the top right cornet of regex101.com, and also a debugger, see: https://regex101.com/r/MkP9cp/1 (Debugger is not available when picking `Golang`, but that should not matter too much when learning regular expressions) – Luuk May 14 '22 at 09:13
  • 2
    `.` matches a single char. `.*` matches any zero or more chars other than line break chars as many as possible, use it. – Wiktor Stribiżew May 14 '22 at 09:19

0 Answers0