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

How to Find Overlapping Matches in Go Strings?

Barbara Streisand
Release: 2024-12-03 21:59:11
Original
885 people have browsed it

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template