Home >Backend Development >Golang >How to Find Overlapping Matches in Go Strings?

How to Find Overlapping Matches in Go Strings?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 21:59:11948browse

How to Find Overlapping Matches in Go Strings?

Finding Overlapping Matches in Go

You want to find the indices of the pattern .#.#.. in a given string, but Go doesn't support overlapping matches in its built-in FindAllStringSubmatchIndex function. To address this, the following answer suggests an alternative approach using strings.Index and a loop instead of regex.

import (
    "fmt"
    "strings"
)

func main() {
    input := "...#...#....#.....#..#..#..#......."
    idx := []int{}
    j := 0

    for {
        i := strings.Index(input[j:], "..#..")
        if i == -1 {
            break
        }

        idx = append(idx, j+i)
        j += i + 1
    }

    fmt.Println("Indexes:", idx)
}

This approach works by iteratively finding the index of the pattern using strings.Index and adding it to the slice of indices until the pattern is no longer found in the input string. It's simpler, more efficient, and avoids the limitations of regex for this specific task.

The above is the detailed content of How to Find Overlapping Matches in Go Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn