Home > Article > Backend Development > 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 := "<h1>Hello World!</h1>"
// 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!