简体   繁体   中英

How to match against multiple characters in a Rust match expression?

I am writing a compiler in Rust. As part of my lexer I'm attempting to match a single character from the input stream against a range of characters (more than one). I'm currently trying an approach using the .. operator.

match input_token {
    'Z'..'a' => { // I want to match any character from 'a' -> 'z' and 'A' -> 'Z' inclusive
        ... run some code
    }
}

Is it possible to match against multiple values in a single arm of a Rust match expression/statement?

The pattern for inclusive ranges is begin..=end and you can combine patterns using |, therefore you want

match input_token {
    'A'..='Z' | 'a'..='z' => {
        ... run some code
    }
}

An alternative is to use an if pattern to handle more complex cases:

match input_token {
    token if token.is_ascii_alphabetic() {
        // ... 
    }
    // ...
}

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