简体   繁体   中英

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. 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:

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.

How do I extract the named parameters in between the brackets into a 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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