英文:
Golang compiled regex to remove " and anything after and including @ in strings
问题
如果我有一个看起来像"Abraham Lincoln" @en
的字符串。我想要做的是,如果它包含@en,则删除引号,但保留内部内容并删除@en。
在golang中,最好的方法是什么?
英文:
If I have a string that looks like "Abraham Lincoln" @en
. What i want to do is if it contains @en then remove the quotes, but keep what is inside and remove @en.
What is the best way to do this in golang?
答案1
得分: 10
你可以根据你的示例输入来实现这个功能。
package main
import (
"fmt"
"regexp"
)
func main() {
s := `"Abraham Lincoln" @en`
reg := regexp.MustCompile(`"([^"]*)" *@en`)
res := reg.ReplaceAllString(s, "")
fmt.Println(res) // Abraham Lincoln
}
如果你有更多跟在引号后面的数据,你可以将表达式改为:
reg := regexp.MustCompile(`"([^"]*)".*@en`)
[kbd]GoPlay[/kbd]
英文:
One way you could do this based off your example input.
package main
import (
"fmt"
"regexp"
)
func main() {
s := `"Abraham Lincoln" @en`
reg := regexp.MustCompile(`"([^"]*)" *@en`)
res := reg.ReplaceAllString(s, "")
fmt.Println(res) // Abraham Lincoln
}
If you have more data that follows the quotes, you could always change the expression to:
reg := regexp.MustCompile(`"([^"]*)".*@en`)
<kbd>GoPlay</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论