在Rust中破坏字符串

问题描述 投票:0回答:1

如何在字符串上进行复杂的模式匹配?像这样的东西:

let res = match data.as_ref() {
    "aaa" => "this is aaa",
    "bbb" => "this is bbb ",
    //...........


    //aaa some_data_here
    "bbb {data2}" => &format!("this is 'bbb' + some data: {}", data2)

    x => &format!("this is not a pattern I know of, it is {}", x),
};
rust
1个回答
0
投票

在Rust中没有内置的东西,所以你必须自己动手。

在简单的情况下,您可以使用切片和辅助方法,如starts_with(),但如果模式更复杂,请尝试使用正则表达式或解析器包。

match支持“警卫”,允许您运行额外的代码来优化匹配:

match string {
  s if s.starts_with("bbb ") => format!("this is 'bbb' + some data: {}", &s[4..])
}
© www.soinside.com 2019 - 2024. All rights reserved.