我有一个用分隔符分隔的字符串.我想用正则表达式拆分这个字符串,并保留分隔符.

我目前的代码是:

use regex::Regex; // 1.1.8

fn main() {
    let seperator = Regex::new(r"([ ,.]+)").expect("Invalid regex");
    let splits: Vec<_> = seperator.split("this... is a, test").into_iter().collect();
    for split in splits {
        println!("\"{}\"", split);
    }
}

其输出为:

"this"
"is"
"a"
"test"

我希望保留分隔符(在本例中为空格字符),我希望看到的输出是:

"this"
"... "
"is"
" "
"a"
", "
"test"

如果可能的话,我怎样才能用regex美元实现这样的行为呢?

这与Split a string keeping the separators不同,后者使用标准库,而不是regex crate .

推荐答案

Regex型上记录的:

Using the std::str::pattern methods with Regex

Note:本节要求使用

由于Regex实现了Pattern,所以可以将正则表达式与方法一起使用

使用pattern功能,您可以使用Split a string keeping the separators中描述的技术:

use regex::Regex; // 1.1.8

fn split_keep<'a>(r: &Regex, text: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();
    let mut last = 0;
    for (index, matched) in text.match_indices(r) {
        if last != index {
            result.push(&text[last..index]);
        }
        result.push(matched);
        last = index + matched.len();
    }
    if last < text.len() {
        result.push(&text[last..]);
    }
    result
}

fn main() {
    let seperator = Regex::new(r"([ ,.]+)").expect("Invalid regex");
    let splits = split_keep(&seperator, "this... is a, test");
    for split in splits {
        println!("\"{}\"", split);
    }
}

这还提示您如何将代码转换为不需要夜间Rust :

例如,[…]find_iter [...] 可替换为[…]str::match_indices

应用反向变换来使用稳定的Regex种方法.

Rust相关问答推荐

if let声明中临时对象的生存期

为什么幻影数据不能自动推断?

在Rust中赋值变量有运行时开销吗?

值为可变对象的不可变HashMap

为什么允许我们将可变引用转换为不可变引用?

有没有办法避免在While循环中多次borrow `*分支`

Pin<;&;mut可能将Uninit<;T>;>;合并为Pin<;&;mut T>;

为什么将易错函数的泛型结果作为泛型参数传递 infer ()?不应该是暧昧的吗?

是否可以在不直接重复的情况下为许多特定类型实现一个函数?

为什么是&mut发送?线程如何在安全的 Rust 中捕获 &mut?

如何从borrow 的异步代码运行阻塞代码?

在Rust中实现Trie数据 struct 的更好方式

从光标位置旋转精灵

切片不能被 `usize` 索引?

n 个范围的笛卡尔积

为什么 Rust 允许写入不可变的 RwLock?

为什么我可以同时传递可变和不可变引用?

Rust HRTB 是相同的,但编译器说一种类型比另一种更通用

在 Rust 中有条件地导入?

返回引用的返回函数