Writing regular expressions

Regular expressions contain a special language, used to write a pattern to extract data from a string. We need three patterns for our example:

  • A path for the index page
  • A path for user management
  • A path for the list of users (a new feature for our example server)

There's a Regex::new function that creates regular expressions. Remove the previous USER_PATH constant and add three new regular expression constants in a lazy static block:

lazy_static! {
static ref INDEX_PATH: Regex = Regex::new("^/(index\.html?)?$").unwrap();
static ref USER_PATH: Regex = Regex::new("^/user/((?P<user_id>\d+?)/?)?$").unwrap();
static ref USERS_PATH: Regex = Regex::new("^/users/?$").unwrap();
}

As you can see, regular expressions look complex. To understand them better, let's analyze them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.134.154