如何在多个分隔符上拆分字符串(String 或 &str)?

How can I split a string (String or &str) on more than one delimiter?

我希望能够在字符串 bbcc 上分隔字符串 aabbaacaaaccaaa,但不能在 bc 上分隔。该示例将导致 aa,aacaaa,aaa.

我已经可以在单个分隔符上拆分字符串,words() 函数在 </code>、<code>\n\t 上拆分字符串,所以我想这一定是可能的。

遗憾的是,您现在无法使用标准库执行此操作。不过,您 可以 在多个 char 分隔符上拆分,就像 words 那样。你需要给 split:

一段字符
for part in "a,bc;d".split(&[',', ';'][..]) {
    println!(">{}<", part);
}

但是,如果您尝试使用字符串:

for part in "a,bc;d".split(&[",", ";"][..]) {
    println!(">{}<", part);
}

你会得到错误:

error[E0277]: expected a `Fn<(char,)>` closure, found `[&str]`
 --> src/main.rs:2:32
  |
2 |     for part in "a,bc;d".split(&[",", ";"][..]) {
  |                                ^^^^^^^^^^^^^^^ expected an `Fn<(char,)>` closure, found `[&str]`
  |
  = help: the trait `Fn<(char,)>` is not implemented for `[&str]`
  = note: required because of the requirements on the impl of `FnOnce<(char,)>` for `&[&str]`
  = note: required because of the requirements on the impl of `Pattern<'_>` for `&[&str]`

在 nightly Rust 中,您可以为自己的类型实现 Pattern,其中包含一段字符串。

如果您喜欢使用不属于标准库且得到良好支持的 crate,您可以使用 regex:

use regex; // 1.4.5

fn main() {
    let re = regex::Regex::new(r"bb|cc").unwrap();
    for part in re.split("aabbaacaaaccaaa") {
        println!(">{}<", part);
    }
}