Golang compiled regex to remove " and anything after and including @ in strings

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

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>

huangapple
  • 本文由 发表于 2014年12月10日 09:53:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/27392130.html
匿名

发表评论

匿名网友

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

确定