-3

I have a string like this:

id=PS\\ Old\\ Gen

and I would to build a regex to find out if it contains a backslash; one after the other. So in this case, the regex should find 2 occurances as there are 2 \\.

I tried building up the query but couldn't figure out the right way.

i need the regex that's compatiable with Go.

kjvf
  • 81
  • 7
  • 2
    Any reason that it must be a regexp? Why not just `strings.Count`? – leaf bebop Feb 05 '19 at 11:02
  • What are you planning to do? Just detect or also change the string? – Dominic Feb 05 '19 at 11:02
  • I need to use the regex in a config file. Just detecting. @Dominic – kjvf Feb 05 '19 at 11:08
  • So you don't need to know how many there are or where they are? Your config file could also just contain a string it doesn't have to be regex does it? Seems better suited to a simple strings function. – Dominic Feb 05 '19 at 11:36

2 Answers2

2

You can use strings.Count(myString, \)

with literal example:

package main

import (
    "fmt"
    "strings"
)

func main() {
    myString := `id=PS\\Old\\Gen`
    a := `\`
    i := strings.Count(myString, a)
    fmt.Println(i)
}

result = 4

without literal

package main

import (
    "fmt"
    "strings"
)

func main() {
    myString := "id=PS\\Old\\Gen"
    a := `\`
    i := strings.Count(myString, a)
    fmt.Println(i)
}

Result=2

if you just need contain use

myString := "id=PS\\ Old\\ Gen"
a:=`\`
i := strings.Contains(myString, a)
fmt.Println(i)

Result=true

Eitam Ring
  • 190
  • 1
  • 10
1

It sounds like you don't need to know the position or occurence of \\ so in that cause I'd suggest going as simple as possible:

import "strings"

...

fmt.Println(strings.Contains("id=PS\\ Old\\ Gen", "\\")) // true

So you can just store "\\" in your config.

Dominic
  • 62,658
  • 20
  • 139
  • 163
  • I have tried that but it complains. It's printing out this: `regexp: Compile(`\`): error parsing regexp: trailing backslash at end of expression: `` ` See this for context: https://community.influxdata.com/t/telegraf-measurement-values-and-strings/6891 – kjvf Feb 05 '19 at 11:44
  • @kjvf are you using `"` or ` (backtick)? – Dominic Feb 05 '19 at 11:53
  • I am using `"`. I think it looks like a bcktick because of my formatting – kjvf Feb 05 '19 at 12:09