Home > Backend Development > Golang > How to Extract a String Between Two Known Characters in Go?

How to Extract a String Between Two Known Characters in Go?

Barbara Streisand
Release: 2024-11-03 04:34:02
Original
269 people have browsed it

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

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

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!

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