Parsing a formatted string

Let’s say I have a string, e.g. somename.yml and I want to parse out the relevant part.

fmt.Sscanf doesn’t work for this, because it expects spaces at the end of a %s.

regexp works (MustCompile(`(\w+).yml`).FindStringSubmatch) but it feels a bit heavy-handed, and it’s awkward to write.

Is there a lighter-weight way to do this?

If your string is a file name, and your relevant part is the one without the extension, you can get the extension by filepath.Ext and then chop that off the end.

1 Like

This also happens with parts of URLs, though - e.g. /section/23-slug . Anything better than regexing it? Because I need to edit that regexp pretty soon.

It’s super unclear to me what part of what type of string you want to extract. :slight_smile:

https://play.golang.org/p/cR7ua0QvyQ

Hey @riking,

Not sure if this is what you’re looking for, but you could use something simple like this to retrieve the parts that you wanted from a slug like you posted.

package main

import (
	"fmt"
	"strings"
)

func main() {
	slug := "/section/23-slug"

	parts := strings.Split(strings.Trim(slug, "/"), "/")

	fmt.Println(parts)

	for _, part := range parts {
		fmt.Println(part)
	}
}

Yep, that looks like the best route. Slice it up in the expected format.

Glad I could help.
If you want to specifically get the last element from the parts slice in my example above you can use:

fmt.Println(parts[len(parts) - 1])

I see two general options here.

  1. Use the methods from the strings or bytes package to chop the string into the relevant parts.

    or

  2. Embrace regular expressions. Once mastered, they can be a valuable tool for many situations where you otherwise would have to resort to hand-crafting some algorithm, maybe ending up with ugly, deeply nested if-then-else cascades that may be more difficult to maintain than a single regular expression.
    I admit that regexps are not easy, but there are lots of docs out there and even a couple of online regexp editors/testers that may help coming up to speed.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.