Teymour
Teymour

Reputation: 2079

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

I would like to match a single character 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?

Upvotes: 7

Views: 15075

Answers (2)

L. F.
L. F.

Reputation: 20569

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

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

Upvotes: 3

mcarton
mcarton

Reputation: 29981

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
    }
}

Upvotes: 14

Related Questions