Home >Backend Development >Golang >How to Extract a Substring Between Delimiters in Go?

How to Extract a Substring Between Delimiters in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 13:34:01846browse

How to Extract a Substring Between Delimiters in Go?

Extracting a String Between Delimiters in Go

In Go, you may encounter situations where you need to extract a specific substring from a larger string, based on known delimiters or specific characters.

Consider the following string:

<h1>Hello World!</h1>

To extract "Hello World!" from this string using Go, you can employ the following technique:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "&lt;h1&gt;Hello World!&lt;/h1&gt;"

    // Find the index of the starting delimiter
    startIndex := strings.Index(str, "<h1>")

    // If the delimiter is not found, return an empty string
    if startIndex == -1 {
        fmt.Println("No starting delimiter found")
        return
    }

    // Adjust the starting index to omit the delimiter
    startIndex += len("<h1>")

    // Find the index of the ending delimiter
    endIndex := strings.Index(str, "</h1>")

    // If the delimiter is not found, return an empty string
    if endIndex == -1 {
        fmt.Println("No ending delimiter found")
        return
    }

    // Extract the substring between the delimiters
    result := str[startIndex:endIndex]

    // Print the extracted string
    fmt.Println(result)
}

This code finds the indices of the starting and ending delimiters within the input string. It then adjusts the starting index to account for the delimiter and extracts the substring between the delimiters. The extracted substring is then printed to the console.

In general, you can modify the delimiter strings provided in the code to extract specific substrings from any string.

The above is the detailed content of How to Extract a Substring Between Delimiters in Go?. 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