Trying to understand Regex is_match

extern crate regex; // 1.3.5
use regex::Regex; // 1.3.5
fn main() {
    let question_loud = Regex::new(r"[A-Z ]+?$").unwrap();
    assert_eq!(question_loud.is_match("WHAT ARE YOU DOING?"), true);
    assert_eq!(question_loud.is_match("How old are you, 15?"), false);
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.81s
     Running `target/debug/playground`
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `false`,
 right: `true`', src/main.rs:5:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Hi all, why my assertion failed? I thought [A-Z ]+? match at least one uppercase character or space, and follow by a question mark.

Question mark is the regex metacharacter, so it must be escaped to match literally:


use regex::Regex; // 1.3.5
fn main() {
    let question_loud = Regex::new(r"[A-Z ]+\?$").unwrap();
    assert_eq!(question_loud.is_match("WHAT ARE YOU DOING?"), true);
    assert_eq!(question_loud.is_match("How old are you, 15?"), false);
}

Thanks a lot!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.