Go:从两个字符或其他字符串之间检索一个字符串

huangapple go评论101阅读模式
英文:

Go: Retrieve a string from between two characters or other strings

问题

让我们假设我有一个字符串,像这样:

  1. <h1>Hello World!</h1>

有什么Go代码可以从该字符串中提取出Hello World!?我对Go还比较新手。非常感谢您的帮助!

英文:

Let's say for example that I have one string, like this:

  1. &lt;h1&gt;Hello World!&lt;/h1&gt;

What Go code would be able to extract Hello World! from that string? I'm still relatively new to Go. Any help is greatly appreciated!

答案1

得分: 19

如果字符串看起来像是任意内容;START;提取;END;任意内容,你可以使用以下代码来获取两者之间的字符串:

  1. // GetStringInBetween 如果没有找到起始字符串,则返回空字符串
  2. func GetStringInBetween(str string, start string, end string) (result string) {
  3. s := strings.Index(str, start)
  4. if s == -1 {
  5. return
  6. }
  7. s += len(start)
  8. e := strings.Index(str[s:], end)
  9. if e == -1 {
  10. return
  11. }
  12. e += s + e - 1
  13. return str[s:e]
  14. }

这里的逻辑是,它会找到第一个 START 的索引,加上 START 字符串的长度,并返回从那里开始直到第一个 END 索引的所有内容。

英文:

If the string looks like whatever;START;extract;END;whatever you can use this which will get the string in between:

  1. // GetStringInBetween Returns empty string if no start string found
  2. func GetStringInBetween(str string, start string, end string) (result string) {
  3. s := strings.Index(str, start)
  4. if s == -1 {
  5. return
  6. }
  7. s += len(start)
  8. e := strings.Index(str[s:], end)
  9. if e == -1 {
  10. return
  11. }
  12. e += s + e - 1
  13. return str[s:e]
  14. }

What happens here is it will find first index of START, adds length of START string and returns all that exists from there until first index of END.

答案2

得分: 14

在所有编程语言中,有很多方法可以拆分字符串。

由于我不知道你具体在问什么,我提供一个示例方法来获取你想要的输出。

  1. package main
  2. import "strings"
  3. import "fmt"
  4. func main() {
  5. initial := "<h1>Hello World!</h1>"
  6. out := strings.TrimLeft(strings.TrimRight(initial,"</h1>"),"<h1>")
  7. fmt.Println(out)
  8. }

在上面的代码中,你从字符串的左侧删除了<h1>,从右侧删除了</h1>

正如我所说,有数百种方法可以拆分特定的字符串,这只是一个让你入门的示例。

希望对你有帮助,祝你在Golang中好运!

DB

英文:

There are lots of ways to split strings in all programming languages.

Since I don't know what you are especially asking for I provide a sample way to get the output
you want from your sample.

  1. package main
  2. import &quot;strings&quot;
  3. import &quot;fmt&quot;
  4. func main() {
  5. initial := &quot;&lt;h1&gt;Hello World!&lt;/h1&gt;&quot;
  6. out := strings.TrimLeft(strings.TrimRight(initial,&quot;&lt;/h1&gt;&quot;),&quot;&lt;h1&gt;&quot;)
  7. fmt.Println(out)
  8. }

In the above code you trim &lt;h1&gt; from the left of the string and &lt;/h1&gt; from the right.

As I said there are hundreds of ways to split specific strings and this is only a sample to get you started.

Hope it helps, Good luck with Golang Go:从两个字符或其他字符串之间检索一个字符串

DB

答案3

得分: 6

我改进了Jan Kardaš的答案。
现在你可以在开头和结尾找到多于一个字符的字符串。

  1. func GetStringInBetweenTwoString(str string, startS string, endS string) (result string, found bool) {
  2. s := strings.Index(str, startS)
  3. if s == -1 {
  4. return result, false
  5. }
  6. newS := str[s+len(startS):]
  7. e := strings.Index(newS, endS)
  8. if e == -1 {
  9. return result, false
  10. }
  11. result = newS[:e]
  12. return result, true
  13. }
英文:

I improved the Jan Kardaš`s answer.
now you can find string with more than 1 character at the start and end.

  1. func GetStringInBetweenTwoString(str string, startS string, endS string) (result string,found bool) {
  2. s := strings.Index(str, startS)
  3. if s == -1 {
  4. return result,false
  5. }
  6. newS := str[s+len(startS):]
  7. e := strings.Index(newS, endS)
  8. if e == -1 {
  9. return result,false
  10. }
  11. result = newS[:e]
  12. return result,true
  13. }

答案4

得分: 6

这是我使用正则表达式的答案。不确定为什么没有人建议这种最安全的方法。

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. content := "<h1>Hello World!</h1>"
  8. re := regexp.MustCompile(`<h1>(.*)</h1>`)
  9. match := re.FindStringSubmatch(content)
  10. if len(match) > 1 {
  11. fmt.Println("找到匹配 -", match[1])
  12. } else {
  13. fmt.Println("未找到匹配")
  14. }
  15. }

Playground - https://play.golang.org/p/Yc61x1cbZOJ

英文:

Here is my answer using regex. Not sure why no one suggested this safest approach

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;regexp&quot;
  5. )
  6. func main() {
  7. content := &quot;&lt;h1&gt;Hello World!&lt;/h1&gt;&quot;
  8. re := regexp.MustCompile(`&lt;h1&gt;(.*)&lt;/h1&gt;`)
  9. match := re.FindStringSubmatch(content)
  10. if len(match) &gt; 1 {
  11. fmt.Println(&quot;match found -&quot;, match[1])
  12. } else {
  13. fmt.Println(&quot;match not found&quot;)
  14. }
  15. }

Playground - https://play.golang.org/p/Yc61x1cbZOJ

答案5

得分: 2

strings包中,你可以使用Replacer来产生很大的影响。

  1. r := strings.NewReplacer("<h1>", "", "</h1>", "")
  2. fmt.Println(r.Replace("<h1>Hello World!</h1>"))

试试吧!

英文:

In the strings pkg you can use the Replacer to great affect.

  1. r := strings.NewReplacer(&quot;&lt;h1&gt;&quot;, &quot;&quot;, &quot;&lt;/h1&gt;&quot;, &quot;&quot;)
  2. fmt.Println(r.Replace(&quot;&lt;h1&gt;Hello World!&lt;/h1&gt;&quot;))

Go play!

答案6

得分: 2

  1. func findInString(str, start, end string) ([]byte, error) {
  2. var match []byte
  3. index := strings.Index(str, start)
  4. if index == -1 {
  5. return match, errors.New("Not found")
  6. }
  7. index += len(start)
  8. for {
  9. char := str[index]
  10. if strings.HasPrefix(str[index:index+len(match)], end) {
  11. break
  12. }
  13. match = append(match, char)
  14. index++
  15. }
  16. return match, nil
  17. }
  1. func findInString(str, start, end string) ([]byte, error) {
  2. var match []byte
  3. index := strings.Index(str, start)
  4. if index == -1 {
  5. return match, errors.New("未找到")
  6. }
  7. index += len(start)
  8. for {
  9. char := str[index]
  10. if strings.HasPrefix(str[index:index+len(match)], end) {
  11. break
  12. }
  13. match = append(match, char)
  14. index++
  15. }
  16. return match, nil
  17. }
英文:
  1. func findInString(str, start, end string) ([]byte, error) {
  2. var match []byte
  3. index := strings.Index(str, start)
  4. if index == -1 {
  5. return match, errors.New(&quot;Not found&quot;)
  6. }
  7. index += len(start)
  8. for {
  9. char := str[index]
  10. if strings.HasPrefix(str[index:index+len(match)], end) {
  11. break
  12. }
  13. match = append(match, char)
  14. index++
  15. }
  16. return match, nil
  17. }

答案7

得分: 1

请阅读一下strings包的相关文档。查看一下SplitAfter函数,它可以实现以下功能:

  1. var sample = "[this][is my][string]"
  2. t := strings.SplitAfter(sample, "[")

这样应该会生成一个类似这样的切片:"[", "this][", "is my][", "string]"。使用进一步的修剪函数,你应该能够得到你想要的解决方案。祝你好运。

英文:

Read up on the strings package. Have a look into the SplitAfter function which can do something like this:

  1. var sample = &quot;[this][is my][string]&quot;
  2. t := strings.SplitAfter(sample, &quot;[&quot;)

That should produce a slice something like: &quot;[&quot;, &quot;this][&quot;, &quot;is my][&quot;, &quot;string]&quot;. Using further functions for Trimming you should get your solution. Best of luck.

答案8

得分: 0

  1. func Split(str, before, after string) string {
  2. a := strings.SplitAfterN(str, before, 2)
  3. b := strings.SplitAfterN(a[len(a)-1], after, 2)
  4. if len(b) == 1 {
  5. return b[0]
  6. }
  7. return b[0][0 : len(b[0])-len(after)]
  8. }

SplitAfterN函数的第一次调用将原始字符串分割成两部分的数组,这两部分由第一个找到的after字符串分隔,或者它将生成包含一个与原始字符串相等的部分的数组。

SplitAfterN的第二次调用使用a[len(a)-1]作为输入,因为它是“数组a的最后一项”。所以输入将被分割成两部分的数组,这两部分由第一个找到的before字符串分隔,或者它将生成包含一个与输入相等的部分的数组。

如果没有找到after,我们可以简单地返回b[0],因为它等于a[len(a)-1]

如果找到了after,它将包含在b[0]字符串的末尾,因此您需要通过b[0][0:len(b[0])-len(after)]来修剪它。

所有字符串都区分大小写。

英文:
  1. func Split(str, before, after string) string {
  2. a := strings.SplitAfterN(str, before, 2)
  3. b := strings.SplitAfterN(a[len(a)-1], after, 2)
  4. if 1 == len(b) {
  5. return b[0]
  6. }
  7. return b[0][0:len(b[0])-len(after)]
  8. }

the first call of SplitAfterN will split the original string into array of 2 parts divided by the first found after string, or it will produce array containing 1 part equal to the original string.

second call of SplitAfterN uses a[len(a)-1] as input, as it is "the last item of array a". so either string after after or the original string str. the input will be split into array of 2 parts divided by the first found before string, or it will produce array containing 1 part equal to the input.

if after was not found than we can simply return b[0] as it is equal to a[len(a)-1]

if after is found, it will be included at the end of b[0] string, therefore you have to trim it via b[0][0:len(b[0])-len(after)]

all strings are case sensitive

答案9

得分: 0

  1. func SplitBetween(str, bef, aft string) string {
  2. sa := strings.SplitN(str, bef, 2)
  3. if len(sa) == 1 {
  4. return ""
  5. }
  6. sa = strings.SplitN(sa[1], aft, 2)
  7. if len(sa) == 1 {
  8. return ""
  9. }
  10. return sa[0]
  11. }

如果找不到分割点,则返回空字符串。

英文:

How about:

  1. func SplitBetween(str, bef, aft string) string {
  2. sa := strings.SplitN(str, bef, 2)
  3. if len(sa) == 1 {
  4. return &quot;&quot;
  5. }
  6. sa = strings.SplitN(sa[1], aft, 2)
  7. if len(sa) == 1 {
  8. return &quot;&quot;
  9. }
  10. return sa[0]
  11. }

Returns empty string if split is not found.

huangapple
  • 本文由 发表于 2014年11月14日 03:35:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/26916952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定