Skip to content

str::matches

str methods · Strings

Level: reference · for working programmers

One line: An iterator over the matched substrings themselves — the pieces the pattern hit, not the gaps between them.

pub fn matches<P: Pattern>(&self, pat: P) -> Matches<'_, P>

Stable since 1.2.0.

split yields what is between the matches; matches yields the matches. n matches always give n items here and n+1 pieces there, which is the arithmetic behind every surprising empty string in a split.

s.matches(p).count() is how you count occurrences. Matches do not overlap and are found left to right, so "aaaa".matches("aa") is 2, not 3.

With a &str pattern every item is the same text and the useful part is the count. It gets interesting with a &[char] or a predicate, where each item tells you which character matched:

fn main() {
    let vowels: String = "programming".matches(|c| "aeiou".contains(c)).collect();
    println!("{vowels}");  // oai
}

Example

str_matches.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let s = "the rain in spain";

    println!("{:?}", s.matches("in").collect::<Vec<&str>>());
    println!("{} matches, {} pieces", s.matches("in").count(), s.split("in").count());

    // Matches do not overlap.
    println!("{:?}", "aaaa".matches("aa").collect::<Vec<&str>>());

    // A predicate pattern reports which character matched.
    println!("{:?}", s.matches(|c: char| "aeiou".contains(c)).collect::<Vec<&str>>());

    // A set of characters.
    println!("{:?}", "a1b2c3".matches(char::is_numeric).collect::<Vec<&str>>());

    // Counting occurrences is the everyday use.
    println!("{}", "banana".matches('a').count());
}

Verified output of str_matches.rs — regenerated by tools/run_examples.py, never hand-typed.

["in", "in", "in"]
3 matches, 4 pieces
["aa", "aa"]
["e", "a", "i", "i", "a", "i"]
["1", "2", "3"]
3

See also

str::matches in the standard library ↗

Po polsku

matches zwraca same trafienia, a split — kawałki między nimi; stąd arytmetyka z wydruku: trzy dopasowania „in”, ale cztery fragmenty po podziale, i to właśnie ta różnica n kontra n+1 stoi za każdym zaskakującym pustym łańcuchem znaków w wyniku split. Dopasowania nie nachodzą na siebie i są szukane od lewej, więc "aaaa".matches("aa") daje 2, a nie 3 — o tym trzeba pamiętać, licząc wystąpienia przez .count(). Jeżeli szukasz w bibliotece standardowej wyrażeń regularnych, to ich tam nie ma: najbliższym odpowiednikiem Pythonowego re.findall jest matches z domknięciem (closure) albo ze zbiorem znaków &[char], gdzie każdy element mówi, który znak pasował — jak w linii zwracającej ["e", "a", "i", "i", "a", "i"]. Do prawdziwych wzorców trzeba sięgnąć po osobny crate regex.

Szukaj po polsku: zliczanie wystąpień podłańcucha · wyrażenia regularne w Ruście · rust str matches count occurrences · rust regex crate