A few examples of regular expression and the RegExp
class in Flutter and Dart.
Example 1: Email Validation
The code:
// kindacode.com
import 'package:flutter/foundation.dart';
void main() {
RegExp exp = RegExp(
r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$",
caseSensitive: false);
// Try it
String email1 = "[email protected]";
String email2 = "test@gmail";
String email3 = "test#gmail.com";
if (exp.hasMatch(email1)) {
if (kDebugMode) {
print("Email1 OK");
}
}
if (exp.hasMatch(email2)) {
if (kDebugMode) {
print("Email2 OK");
}
}
if (exp.hasMatch(email3)) {
if (kDebugMode) {
print("Email3 OK");
}
}
}
Output:
Email1 OK
Email2 OK
Example 2: IP Addresses Validation
The code:
// kindacode.com
import 'package:flutter/foundation.dart';
void main() {
RegExp ipExp = 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')) {
if (kDebugMode) {
print('192.168.1.2 is valid');
}
}
// Expectation: false
if (ipExp.hasMatch('192.168.111111.55555')) {
if (kDebugMode) {
print('192.168.111111.55555 is valid');
}
}
}
Output:
192.168.1.2 is valid
Example 3: URL validation
The code:
// kindacode.com
import 'package:flutter/foundation.dart';
void main() {
RegExp urlExp = RegExp(
r"(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?");
String url1 = "https://www.kindacode.com/cat/mobile/flutter/"; // valid
String url2 = "https://kindacode/cat/mobile/flutter/"; // invalid
if (urlExp.hasMatch(url1)) {
if (kDebugMode) {
print('Url1 looks good!');
}
}
if (urlExp.hasMatch(url2)) {
if (kDebugMode) {
print("Url2 looks good!");
}
}
}
Output:
Url1 looks good!
Example 4: Domain validation
// kindacode.com
import 'package:flutter/foundation.dart';
void main() {
RegExp domainExp = RegExp(r"^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}$");
String domain1 = "www.kindacode.com"; // expected: valid
String domain2 = "www.amazon.co.uk"; // expected: valid
String domain3 = "hello world!"; // expected: invalid
if (domainExp.hasMatch(domain1)) {
if (kDebugMode) {
print('domain1 is valid');
}
}
if (domainExp.hasMatch(domain2)) {
if (kDebugMode) {
print('domain2 is valid');
}
}
if (domainExp.hasMatch(domain3)) {
if (kDebugMode) {
print('domain3 is valid');
}
}
}
Output:
domain1 is valid
domain2 is valid
Wrap Up
We’ve reviewed a few examples of using regular expressions in Dart that may be very helpful in many everyday use cases. If you’d like to learn more about Dart and Flutter, take a look at the following articles:
- Flutter: FilteringTextInputFormatter Examples
- Flutter form validation example
- Flutter & SQLite: CRUD Example
- How to create a Filter/Search ListView in Flutter
- Dart: Converting a List to a Map and Vice Versa
- Dart: Sorting Entries of a Map by Its Values
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.