T14*_*145 2 string substring go
比方说我有一个字符串,如下所示:
<h1>Hello World!</h1>
Run Code Online (Sandbox Code Playgroud)
什么Go代码能够Hello World!从该字符串中提取?我还是比较新的Go.任何帮助是极大的赞赏!
小智 9
有很多方法可以在所有编程语言中拆分字符串.
因为我不知道你是什么特别要求我提供一个样本方法来从你的样本中获得你想要的输出.
package main
import "strings"
import "fmt"
func main() {
initial := "<h1>Hello World!</h1>"
out := strings.TrimLeft(strings.TrimRight(initial,"</h1>"),"<h1>")
fmt.Println(out)
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,您可以<h1>从字符串的左侧和</h1>右侧进行修剪.
正如我所说,有数百种方法可以分割特定的字符串,这只是一个让你入门的例子.
希望它有所帮助,祝你好运Golang :)
D B
小智 9
如果字符串看起来像什么; START;提取; END;无论可以使用什么:
// 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, end)
if e == -1 {
return
}
return str[s:e]
}
Run Code Online (Sandbox Code Playgroud)
这里发生的是它将找到START的第一个索引,添加START字符串的长度,并从那里返回存在的所有内容,直到END的第一个索引。
我改进了Jan Karda\xc5\xa1答案。\n现在您可以找到开头和结尾有超过 1 个字符的字符串。
func GetStringInBetweenTwoString(str string, startS string, endS string) (result string,found bool) {\n s := strings.Index(str, startS)\n if s == -1 {\n return result,false\n }\n newS := str[s+len(startS):]\n e := strings.Index(newS, endS)\n if e == -1 {\n return result,false\n }\n result = newS[:e]\n return result,true\n}\nRun Code Online (Sandbox Code Playgroud)\n
这是我使用正则表达式的答案。不知道为什么没有人建议这种最安全的方法
package main
import (
"fmt"
"regexp"
)
func main() {
content := "<h1>Hello World!</h1>"
re := regexp.MustCompile(`<h1>(.*)</h1>`)
match := re.FindStringSubmatch(content)
if len(match) > 1 {
fmt.Println("match found -", match[1])
} else {
fmt.Println("match not found")
}
}
Run Code Online (Sandbox Code Playgroud)
游乐场 - https://play.golang.org/p/Yc61x1cbZOJ