Go 等效于 C 的否定扫描集

Go equivalent of C's negated scansets

模仿C中存在的否定扫描集的方法是什么?

例如输入字符串:aaaa, bbbb

正在使用:

fmt.Sscanf(input, "%s, %s", &str1, &str2)

结果只有str1被设置为:aaaa,

在 C 中可以使用格式字符串 "%[^,], %s" 来避免这个问题,有没有办法在 go 中完成这个?

你总是可以使用正则表达式;

re := regexp.MustCompile(`(\w+), (\w+)`)
input := "aaaa, bbbb"
fmt.Printf("%#v\n", re.FindStringSubmatch(input))
// Prints []string{"aaaa, bbbb", "aaaa", "bbbb"}

Go 不像 C 那样直接支持它,部分原因是你应该阅读一行并使用类似 strings.FieldsFunc 的东西。但这自然是一种非常简单的观点。对于以同类方式格式化的数据,您可以使用 bufio.Scanner 对任何 io.Reader 进行本质上相同的操作。但是,如果您必须处理类似这种格式的内容:

// Name; email@domain
//
// Anything other than ';' is valid for name.
// Anything before '@' is valid for email.
// For domain, only A-Z, a-z, and 0-9, as well as '-' and '.' are valid.
sscanf("%[^;]; %[^@]@%[-." ALNUM "]", name, email, domain);

然后你会 运行 陷入麻烦,因为你现在正在处理一个特定的状态。在这种情况下,您可能更喜欢使用 bufio.Reader 来手动解析内容。还有实施 fmt.Scanner 的选项。下面是一些示例代码,让您了解实现 fmt.Scanner:

是多么容易
// Scanset acts as a filter when scanning strings.
// The zero value of a Scanset will discard all non-whitespace characters.
type Scanset struct {
    ps        *string
    delimFunc func(rune) bool
}

// Create a new Scanset to filter delimiter characters.
// Once f(delimChar) returns false, scanning will end.
// If s is nil, characters for which f(delimChar) returns true are discarded.
// If f is nil, !unicode.IsSpace(delimChar) is used
// (i.e. read until unicode.IsSpace(delimChar) returns true).
func NewScanset(s *string, f func(r rune) bool) *Scanset {
    return &Scanset{
        ps:        s,
        delimFunc: f,
    }
}

// Scan implements the fmt.Scanner interface for the Scanset type.
func (s *Scanset) Scan(state fmt.ScanState, verb rune) error {
    if verb != 'v' && verb != 's' {
        return errors.New("scansets only work with %v and %s verbs")
    }
    tok, err := state.Token(false, s.delimFunc)
    if err != nil {
        return err
    }
    if s.ps != nil {
        *s.ps = string(tok)
    }
    return nil
}

Playground example

这不是 C 的扫描集,但已经足够接近了。如前所述,无论如何你都应该验证你的数据,即使是格式化输入,因为格式化缺乏上下文(并且在处理格式化时添加它违反了 KISS 原则并降低了代码的可读性)。

例如,像 [A-Za-z]([A-Za-z0-9-]?.)[A-Za-z0-9] 这样的短正则表达式不足以验证域名,而简单的扫描集就相当于 [A-Za-z0-9.-]。然而,扫描集足以从文件或您可能使用的任何其他 reader 扫描字符串,但不足以单独验证字符串。为此,正则表达式甚至适当的库将是更好的选择。