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

10,642

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, "${1}")
   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`)

GoPlay

Share:
10,642
wordSmith
Author by

wordSmith

Updated on June 05, 2022

Comments

  • wordSmith
    wordSmith almost 2 years

    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?

    • Avinash Raj
      Avinash Raj over 9 years
      What's your expected output?
    • wordSmith
      wordSmith over 9 years
      @AvinashRaj In that case Abraham Lincoln
    • hwnd
      hwnd over 9 years
      @AvinashRaj I just finished a version of the regex explainer as a chrome extension.
    • hwnd
      hwnd over 9 years
      Not as of yet. I'll have to implement that next. If you use chrome, look at my profile the link and screenshot is in it.
    • Avinash Raj
      Avinash Raj over 9 years
      ok, i'll try that...