Home >Backend Development >Golang >How to Extract a String Between Two Known Characters in Go?
Extracting Strings from Within a String in Go
Suppose you have a string like this:
<h1>Hello World!</h1>
How would you extract "Hello World!" from it using Go? This question is particularly relevant to Go beginners.
Solution:
To retrieve a specific string between two known characters or strings, you can leverage the following Go code:
<code class="go">// GetStringInBetween returns an empty string if no start string is found func GetStringInBetween(str, start, end string) 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>
Explanation:
This code starts by finding the index of the 'start' string within the larger string. If not found, an empty string is returned. It then increments the index by the length of the 'start' string to point to the first character after 'start'.
Next, it finds the index of the 'end' string within the substring starting from the previous point. If not found, an empty string is returned again.
Finally, the code calculates the length of the desired substring by adding the lengths of 'start' and 'end' to the index of 'end'. It then uses this length to extract the string from the substring.
The above is the detailed content of How to Extract a String Between Two Known Characters in Go?. For more information, please follow other related articles on the PHP Chinese website!