Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split by an unknown number of tabs, spaces, and newlines in Rust?

Tags:

rust

I want to achieve something very similar to strings.Fields in Go where I get all the non \t , space and \n consecutive character in a line

For example

this is a \n special \t\t word

will return

[this, is, a, special, word]

Is that possible in Rust?

The split function only takes an explicit pattern.

For example

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

with

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

will return

a
b
\t
c
like image 769
Jal Avatar asked Oct 20 '25 12:10

Jal


1 Answers

The split_whitespace method defined on str in the standard library will do what you want.

The example from the documentation is pretty clear:

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());
like image 140
BurntSushi5 Avatar answered Oct 23 '25 04:10

BurntSushi5