英文:
Go: Retrieve a string from between two characters or other strings
问题
让我们假设我有一个字符串,像这样:
<h1>Hello World!</h1>
有什么Go代码可以从该字符串中提取出Hello World!
?我对Go还比较新手。非常感谢您的帮助!
英文:
Let's say for example that I have one string, like this:
<h1>Hello World!</h1>
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;任意内容,你可以使用以下代码来获取两者之间的字符串:
// GetStringInBetween 如果没有找到起始字符串,则返回空字符串
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]
}
这里的逻辑是,它会找到第一个 START 的索引,加上 START 字符串的长度,并返回从那里开始直到第一个 END 索引的所有内容。
英文:
If the string looks like whatever;START;extract;END;whatever you can use this which will get the string in between:
// 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]
}
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
在所有编程语言中,有很多方法可以拆分字符串。
由于我不知道你具体在问什么,我提供一个示例方法来获取你想要的输出。
package main
import "strings"
import "fmt"
func main() {
initial := "<h1>Hello World!</h1>"
out := strings.TrimLeft(strings.TrimRight(initial,"</h1>"),"<h1>")
fmt.Println(out)
}
在上面的代码中,你从字符串的左侧删除了<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.
package main
import "strings"
import "fmt"
func main() {
initial := "<h1>Hello World!</h1>"
out := strings.TrimLeft(strings.TrimRight(initial,"</h1>"),"<h1>")
fmt.Println(out)
}
In the above code you trim <h1>
from the left of the string and </h1>
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
DB
答案3
得分: 6
我改进了Jan Kardaš
的答案。
现在你可以在开头和结尾找到多于一个字符的字符串。
func GetStringInBetweenTwoString(str string, startS string, endS string) (result string, found bool) {
s := strings.Index(str, startS)
if s == -1 {
return result, false
}
newS := str[s+len(startS):]
e := strings.Index(newS, endS)
if e == -1 {
return result, false
}
result = newS[:e]
return result, true
}
英文:
I improved the Jan Kardaš
`s answer.
now you can find string with more than 1 character at the start and end.
func GetStringInBetweenTwoString(str string, startS string, endS string) (result string,found bool) {
s := strings.Index(str, startS)
if s == -1 {
return result,false
}
newS := str[s+len(startS):]
e := strings.Index(newS, endS)
if e == -1 {
return result,false
}
result = newS[:e]
return result,true
}
答案4
得分: 6
这是我使用正则表达式的答案。不确定为什么没有人建议这种最安全的方法。
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[1])
} else {
fmt.Println("未找到匹配")
}
}
Playground - https://play.golang.org/p/Yc61x1cbZOJ
英文:
Here is my answer using regex. Not sure why no one suggested this safest approach
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")
}
}
Playground - https://play.golang.org/p/Yc61x1cbZOJ
答案5
得分: 2
在strings包中,你可以使用Replacer来产生很大的影响。
r := strings.NewReplacer("<h1>", "", "</h1>", "")
fmt.Println(r.Replace("<h1>Hello World!</h1>"))
去试试吧!
英文:
In the strings pkg you can use the Replacer to great affect.
r := strings.NewReplacer("<h1>", "", "</h1>", "")
fmt.Println(r.Replace("<h1>Hello World!</h1>"))
Go play!
答案6
得分: 2
func findInString(str, start, end string) ([]byte, error) {
var match []byte
index := strings.Index(str, start)
if index == -1 {
return match, errors.New("Not found")
}
index += len(start)
for {
char := str[index]
if strings.HasPrefix(str[index:index+len(match)], end) {
break
}
match = append(match, char)
index++
}
return match, nil
}
func findInString(str, start, end string) ([]byte, error) {
var match []byte
index := strings.Index(str, start)
if index == -1 {
return match, errors.New("未找到")
}
index += len(start)
for {
char := str[index]
if strings.HasPrefix(str[index:index+len(match)], end) {
break
}
match = append(match, char)
index++
}
return match, nil
}
英文:
func findInString(str, start, end string) ([]byte, error) {
var match []byte
index := strings.Index(str, start)
if index == -1 {
return match, errors.New("Not found")
}
index += len(start)
for {
char := str[index]
if strings.HasPrefix(str[index:index+len(match)], end) {
break
}
match = append(match, char)
index++
}
return match, nil
}
答案7
得分: 1
请阅读一下strings包的相关文档。查看一下SplitAfter函数,它可以实现以下功能:
var sample = "[this][is my][string]"
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:
var sample = "[this][is my][string]"
t := strings.SplitAfter(sample, "[")
That should produce a slice something like: "[", "this][", "is my][", "string]"
. Using further functions for Trimming you should get your solution. Best of luck.
答案8
得分: 0
func Split(str, before, after string) string {
a := strings.SplitAfterN(str, before, 2)
b := strings.SplitAfterN(a[len(a)-1], after, 2)
if len(b) == 1 {
return b[0]
}
return b[0][0 : len(b[0])-len(after)]
}
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)]
来修剪它。
所有字符串都区分大小写。
英文:
func Split(str, before, after string) string {
a := strings.SplitAfterN(str, before, 2)
b := strings.SplitAfterN(a[len(a)-1], after, 2)
if 1 == len(b) {
return b[0]
}
return b[0][0:len(b[0])-len(after)]
}
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
func SplitBetween(str, bef, aft string) string {
sa := strings.SplitN(str, bef, 2)
if len(sa) == 1 {
return ""
}
sa = strings.SplitN(sa[1], aft, 2)
if len(sa) == 1 {
return ""
}
return sa[0]
}
如果找不到分割点,则返回空字符串。
英文:
How about:
func SplitBetween(str, bef, aft string) string {
sa := strings.SplitN(str, bef, 2)
if len(sa) == 1 {
return ""
}
sa = strings.SplitN(sa[1], aft, 2)
if len(sa) == 1 {
return ""
}
return sa[0]
}
Returns empty string if split is not found.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论