O'Reilly logo

Dart: Scalable Application Development by Ivo Balbaert, Sergey Akopkokhyants, Davy Mitchell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using regular expressions

Regular expressions are an indispensable tool in every programming language to search for matching patterns in strings. Dart has the RegExp class from dart:core, which uses the same syntax and semantics as JavaScript.

How to do it...

We use RegExp in the following code (see using_regexp.dart) to quickly determine whether a credit card number seems valid:

var visa = new RegExp(r"^(?:4[0-9]{12}(?:[0-9]{3})?)$");
var visa_in_text = new RegExp(r"\b4[0-9]{12}(?:[0-9]{3})?\b");
var input = "4457418557635128";
var text = "Does this text mention a VISA 4457418557635128 number?";

void main() {
  print(visa.pattern);
  // is there a visa pattern match in input?
  if (visa.hasMatch(input)) { print("Could be a VISA number"); } // does ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required