How I can find matches in this example


(ext) #1

hello please help, here are the raw data:

str: = "fsdfsdfs {% randstr%} dfbdfbdf {% randstr%} gdfgdfg {% randstr%} fsd {% randstr%}"

how do i find and get count the number of {% randstr%} such matches?


(catacombs) #2

If you know % will always have a pair, you could go character by character and get a count of %. Then, because there’s always two, divide the count in half.

package main

import (
	"fmt"
)

func main() {
	str := "fsdfsdfs {% randstr%} dfbdfbdf {% randstr%} gdfgdfg {% randstr%} fsd {% randstr%}"

	count := 0
	for _, value := range str {
		s := string(value)
		if (s == "%") {
			count++
		}
	}
	
	fmt.Printf("Randstr objects: %d", count / 2)
}

(ext) #3

but how can I extract data from brackets right away, I need:
-to count how many elements are found

  • extract data inside {% …%}

(Yamil Bracho) #4

I think you can use strings.Count.

count := strings.Count( str, “{% randstr%}”)


(ext) #5

ок, and how extract data inside {% …%} ?))


(Yamil Bracho) #6

You need to find the token ({%…%} using any of Index function and then take its content. Something like

len := len(token)
for pos := strings.Index(str, token); pos != -1 ; pos = strings.Index(str, token) {
item := strings.TrimSpace(str[pos:pos+len]))
str = strings.TrimSpace(str[pos+len:])
fmt.Println(item)
}


(catacombs) #7
len := len(token)
for pos := strings.Index(str, token); pos != -1 ; pos = strings.Index(str, token) {
    item := strings.TrimSpace(str[pos:pos+len]))
    str = strings.TrimSpace(str[pos+len:])
    fmt.Println(item)
}



(ext) #8

I need something like this, but not working((
https://play.golang.org/p/SOk6BTkno5Y