Search Gear #19 Regular Expressions

func getItem(entries toml.Value) func() (string, error) {
i := -1
return func() (string, error) {
rExpression := regexp.MustCompile("(-([A-Z]+|[A-Z]+[1-9])-)")
i += 1

    if i < len(entries.AsArray()) {
        if rExpression.FindString(entries.AsArray()[i].AsString()) != "" {
            foundString := rExpression.FindString(entries.AsArray()[i].AsString())
            switch foundString {
            case "-YY-":
                replaceWith := strconv.Itoa(time.Now().Year())
                entity := rExpression.ReplaceAllLiteralString(entries.AsArray()[i].AsString(), replaceWith[2:4])
                return entity, nil
            case "-YY1-":
                replaceWith := strconv.Itoa(time.Now().Year() + 1)
                entity := rExpression.ReplaceAllLiteralString(entries.AsArray()[i].AsString(), replaceWith[2:4])
                return entity, nil
            case "-YYYY-":
                replaceWith := strconv.Itoa(time.Now().Year())
                entity := rExpression.ReplaceAllLiteralString(entries.AsArray()[i].AsString(), replaceWith)
                return entity, nil
            case "-YYYY1-":
                replaceWith := strconv.Itoa(time.Now().Year() + 1)
                entity := rExpression.ReplaceAllLiteralString(entries.AsArray()[i].AsString(), replaceWith)
                return entity, nil
            default:
                return entries.AsArray()[i].AsString(), errors.New(co.Lang("wildcard specified but not found in control structure"))
            }
        } else {
            return entries.AsArray()[i].AsString(), nil
        }
    }
    return "", errors.New(co.Lang("end of data"))
}

}

func (tw *twitter) GetTags() (string, error) {
nextItem := getItem(tw.tags)
twAllTags := "twitter tags"

for {
    if entry, err := nextItem(); err != nil {
        if entry == "" {
            break
        }
    } else {
        twTag, _ := tw.collect(entry)
        twAllTags = strings.Join([]string{twAllTags, twTag}, " : ")
    }
}
return twAllTags, nil

}

func (tw *twitter) GetUsers() (string, error) {
nextItem := getItem(tw.users)
twAllUsers := "twitter users"

for {
    if entry, err := nextItem(); err != nil {
        if entry == "" {
            break
        }
    } else {
        twUser, _ := tw.collect(entry)
        twAllUsers = strings.Join([]string{twAllUsers, twUser}, " : ")
    }
}
return twAllUsers, nil

}

func (tw *twitter) GetHome() (string, error) {
return tw.collect("twitter home : ")
}

A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

Also need a clear up function to scrub old files by date.

Gunna be a slow coding week too with meetings getting in the way of gophering!

Leave a comment