Flutter & Dart: Regular Expression Examples

Last updated on September 22, 2021 A Goodman Loading... Post a comment

A few examples of regular expression and the RegExp class in Flutter and Dart.

Example 1: Email Validation

The code:

void main() {
  RegExp exp = new RegExp(
      r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-][email protected][a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$",
      caseSensitive: false);

  // Try it
  String email1 = "[email protected]";
  String email2 = "[email protected]";
  String email3 = "test#gmail.com";

  if (exp.hasMatch(email1)) {
    print("Email1 OK");
  }

  if (exp.hasMatch(email2)) {
    print("Email2 OK");
  }

  if (exp.hasMatch(email3)) {
    print("Email3 OK");
  }
}

Output:

Email1 OK
Email2 OK

Example 2: IP Addresses Validation

The code:

void main() {
  RegExp ipExp = new RegExp(r"^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$", caseSensitive: false, multiLine: false);
  
  // Try it
  // Expectation: true
  if(ipExp.hasMatch('192.168.1.2')){
    print('192.168.1.2 is valid'); 
  }
  
  // Expectation: false
  if(ipExp.hasMatch('192.168.111111.55555')){
    print('192.168.111111.55555 is valid');
  }
}

Output:

192.168.1.2 is valid

Example 3: URL validation

The code:

void main() {
  RegExp urlExp = RegExp(r"(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\[email protected]?^=%&/~+#-])?");
  
  String url1 = "https://www.kindacode.com/cat/mobile/flutter/"; // valid
  
  String url2 = "https://kindacode/cat/mobile/flutter/"; // invalid
  
  if(urlExp.hasMatch(url1)) {
    print('Url1 looks good!');
  }
  
  if(urlExp.hasMatch(url2)) {
    print("Url2 looks good!");
  }
}

Output:

Url1 looks good!

Example 4: Domain validation

void main() {
  RegExp  domainExp = RegExp(r"^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}$");
  
  String domain1 = "www.kindacode.com"; // valid
  String domain2 = "www.amazon.co.uk"; // valid
  String domain3 = "hello world!"; // invalid
  
  if(domainExp.hasMatch(domain1)){
    print('domain1 is valid');
  }
  
  if(domainExp.hasMatch(domain2)){
    print('domain2 is valid');
  }
  
  if(domainExp.hasMatch(domain3)){
    print('domain3 is valid');
  }
}

Output:

domain1 is valid
domain2 is valid

Wrap Up

We’ve gone through a few examples of using regular expression in Dart that may be very helpful in many common use cases. If you’d like to learn more about Dart and Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles