Go Code to Extract Substring Between Two Characters or Strings
If you have a string and want to extract a particular substring from within it, Go provides a flexible mechanism to accomplish this.
For instance, consider the following string:
<h1>Hello World!</h1>
Extracting the Substring
To extract "Hello World!" from this string using Go, you can implement the following function:
<code class="go">// GetStringInBetween Returns empty string if no start string found func GetStringInBetween(str string, start string, end string) (result string) { s := strings.Index(str, start) if s == -1 { return } s += len(start) e := strings.Index(str[s:], end) if e == -1 { return } e += s + e - 1 return str[s:e] }</code>
Understanding the Function
This function takes three arguments:
It works as follows:
Sample Usage
To use this function, you can pass in the original string, the start string, and the end string. For example:
start := "<h1"
end := "</h1>"
substring := GetStringInBetween("<h1>Hello World!</h1>", start, end)
// substring will be "Hello World!"
The above is the detailed content of How to Extract a Substring Between Two Characters or Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!