Home > Backend Development > Golang > How to Extract a Substring Between Two Characters or Strings in Go?

How to Extract a Substring Between Two Characters or Strings in Go?

Barbara Streisand
Release: 2024-11-02 21:27:30
Original
705 people have browsed it

How to Extract a Substring Between Two Characters or Strings in Go?

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

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

Understanding the Function

This function takes three arguments:

  • str: The original string
  • start: The start string or character
  • end: The end string or character

It works as follows:

  1. It finds the first index of start in the original string.
  2. It adds the length of start to the starting index, effectively skipping over the start string.
  3. It finds the first index of end in the substring starting from the adjusted starting index.
  4. It calculates the ending index by adding the adjusted starting index to the found index of end.
  5. Finally, it returns the substring from the adjusted starting index to the ending index.

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("&lt;h1&gt;Hello World!&lt;/h1&gt;", start, end)
// substring will be "Hello World!"
Copy after login

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!

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