Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

go

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?

like image 533
wordSmith Avatar asked Sep 17 '25 11:09

wordSmith


1 Answers

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

like image 166
hwnd Avatar answered Sep 19 '25 04:09

hwnd