-2

I have a long list of numbers where need to quote each number, but I am not sure how to put together a reqex to do it.

I have a list like this

6240, 6261, 6270, 6280, 6510

Which I want to look like this

"6240",1,"6261",1,"6270",1,"6280",1,"6510"

to be able to import it correctly in another tool.

regex is my Nemesis :-)

Morten Hagh
  • 1,853
  • 5
  • 31
  • 57

3 Answers3

2

This can be done with two substitutions. You can first substitute (\d+) with "$1" and then substitute , with ,1,.

blhsing
  • 70,627
  • 6
  • 41
  • 76
0

Posting as an answer because I don't have enough reputation to post comments. For blhsing's attention -- you can do this in a single regex replace, e.g., in python it would look something like:

result = re.sub(r"( +)?(\d+)( +)?", r'"\2",1', subject)

I added some optional elements (( +)?) to account for variable spacing on either side of the numbers.

0

You can get the required result using the below Go Code.

import "fmt"
import "regexp"

func main() {
  str := []string{"6240", "6261", "6270", "6280", "6510"} 
  fmt.Println("Before regex : ",str)
  for i,value := range str{
       r := regexp.MustCompile(value)
       replacer := fmt.Sprintf("%s%s%s%s","\"",value,"\"",",1,")
       str[i] = r.ReplaceAllString(value, replacer)
}
  fmt.Println("After regex  : ",str)   
} 

This Logic Code Works Fine!!