简体   繁体   English

如何使用命名参数解析&str?

[英]How to parse &str with named parameters?

I am trying to find the best way to parse a &str and extract out the COMMAND_TYPE and named parameters.我试图找到解析&str并提取出COMMAND_TYPE和命名参数的最佳方法。 The named parameters can be anything.命名参数可以是任何东西。

Here is the proposed string (it can be changed).这是建议的字符串(可以更改)。

COMMAND_TYPE(param1:2222,param2:"the quick \"brown\" fox, blah,", param3:true)

I have been trying a few ways to extract the COMMAND_TYPE , which seems fairly simple:我一直在尝试几种方法来提取COMMAND_TYPE ,这看起来很简单:

pub fn parse_command(command: &str) -> Option<String> {
    let mut matched = String::new();
    let mut chars = command.chars();

    while let Some(next) = chars.next() {
        if next != '(' {
            matched.push(next);
        } else {
            break;
        }
    }
    if matched.is_empty() {
        None
    } else {
        Some(matched)
    }
}

Extracting the parameters from within the brackets seems straightforward to:从括号内提取参数似乎很简单:

pub fn parse_params(command: &str) -> Option<&str> {
    let start = command.find("(");
    let end = command.rfind(")");

    if start.is_some() && end.is_some() {
        Some(&command[start.unwrap() + 1..end.unwrap()])
    } else {
        None
    }
}

I have been looking at the nom crate and that seems fairly powerful (and complicated), so I am not sure if I really need to use it.我一直在看nom crate,它看起来相当强大(而且很复杂),所以我不确定我是否真的需要使用它。

How do I extract the named parameters in between the brackets into a HashMap ?如何将括号之间的命名参数提取到HashMap

Your code seems to work for extracting the command and the full parameter list.您的代码似乎适用于提取命令和完整参数列表。 If you don't need to parse something more complex than that, you can probably avoid using nom as a dependency.如果您不需要解析比这更复杂的东西,您可能可以避免使用 nom 作为依赖项。

But you will probably have problems if you want to parse individually each parameters : your format seems broken.但是如果您想单独解析每个参数,您可能会遇到问题:您的格式似乎已损坏。 In your example, there is no escape caracters neither for double quote nor comma.在您的示例中,双引号和逗号都没有转义字符。 param2 just can't be extracted cleanly. param2只是不能干净地提取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM