如何在Rust中通过未知数量的制表符、空格和换行符进行分割?

4
我希望实现类似Go语言中的strings.Fields功能,它可以获取一行中所有非\t空格\n连续字符。例如:
this is a \n special \t\t word

将返回

[this, is, a, special, word]

在Rust中是否可能实现这一点?

split 函数只接受显式模式。

例如:

a \t\t\t b \t\t\t\t c

使用

for s in line.split("\t\t\t") {
    println!("{}", s);
}

将返回

a
b
\t
c
1个回答

14

标准库中定义的split_whitespace方法可以实现你想要的功能。

文档中的示例非常清楚:

let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接