如何使用Rust正则表达式分割字符串并保留定界符?

时间:2019-07-07 11:11:50

标签: regex rust

我有一个用定界符分隔的字符串。我想使用正则表达式拆分此字符串并保留定界符。

我当前的代码是:

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,后者使用标准库而不使用正则表达式。

1 个答案:

答案 0 :(得分:3)

根据Regex类型的记录:

  

std::str::pattern方法与Regex一起使用

     
    

注意:本部分要求该板条箱使用     pattern启用了货运功能,需要每晚Rust

  
     

由于Regex实现了Pattern,因此可以将正则表达式与方法配合使用   在&str上定义。例如,is_matchfindfind_iter   和split可以替换为str::containsstr::find,   str::match_indicesstr::split

使用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方法。