Check if an email string matches a basic pattern.

← Operators and Expressions · Ref: Q1100

Regex matching:

  valid <- email matches /[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+/

Regex literals use /slashes/. Returns Boolean. Use 'not matches' for negation. See Q1099 for contains (substring), Q1101 for is in (collection membership).

Example

defines module qa.operators.matchesregex

  defines program

    MatchesRegexDemo()
      stdout <- Stdout()

      email <- "alice@example.com"

      //Match against a basic email pattern
      valid <- email matches /[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+/
      stdout.println(`Valid email: ${valid}`)

      //Non-matching input
      badInput <- "not-an-email"
      invalid <- badInput matches /[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+/
      stdout.println(`Bad input valid: ${invalid}`)

Common mistakes

E50060 — 'matches' takes a RegEx literal (/pattern/), so calling email.matches("...") with a String argument does not resolve. See ek9 -h E50060 for details.

Incorrect:

email.matches("[a-zA-Z]+@[a-zA-Z]+")

Correct:

email matches /[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+/
Other ways to ask this
  • I need to validate a string against a regex pattern in EK9
  • In Python I'd use re.match(). Write the EK9 regex check
  • Given a user input string, test it against a regular expression
  • Validate string format using the matches operator and a regex literal

Coming from another language?

Java: Pattern.matches(regex, str). Python: re.match(pattern, str). Rust: Regex::new(pat).is_match(str). EK9: str matches /pattern/ — inline regex literal.

Keywords: regular expression, pattern, format, validate, regex, matches