Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Dart Tutorial

Dart HOME Dart Intro Dart Get Started Dart Syntax Dart Output Dart Comments Dart Variables Dart final and const Dart Data Types Dart Numbers Dart Strings Dart String Interpolation Dart String Methods Dart Booleans Dart Type Conversion Dart Null Safety Dart late Dart Operators Dart Arithmetic Dart Assignment Dart Comparison Dart Logical Dart Type Test Dart Null Operators Dart Cascade Dart If...Else Dart Switch Dart While Loop Dart For Loop Dart Break/Continue

Dart Collections

Dart Lists Dart Access List Items Dart Change List Items Dart Loop Lists Dart List Methods Dart Sets Dart Maps Dart Access Map Items Dart Loop Maps Dart Collection if/for Dart Spread Operator

Dart Functions

Dart Functions Dart Parameters Dart Named Parameters Dart Return Values Dart Arrow Functions Dart Anonymous Functions Dart Closures Dart Scope Dart Recursion

Dart Classes

Dart OOP Dart Classes/Objects Dart Constructors Dart Named Constructors Dart Factory Constructors Dart Getters and Setters Dart Static Members Dart Inheritance Dart Abstract Classes Dart Interfaces Dart Mixins Dart Extension Methods Dart Enums Dart Generics

Dart 3 Features

Dart Records Dart Patterns Dart Switch Expressions Dart Sealed Classes Dart Class Modifiers

Dart Errors

Dart Exceptions Dart Custom Exceptions

Dart Async

Dart Async Intro Dart Futures Dart async/await Dart Streams Dart Isolates

Dart Libraries

Dart Imports Dart Packages Dart Math Dart Dates Dart JSON Dart RegExp Dart User Input Dart Files Dart Testing

Dart Examples

Dart Examples Dart Exercises


Dart RegExp


Share

Dart RegExp

A regular expression is a pattern that describes some text.

You can use it to check if a string has a certain form, like an email address or a phone number, or to find and replace parts of a string.

In Dart, a regular expression is an object of the RegExp class.

It is part of dart:core, so you do not need an import.


Create a RegExp

To create a regular expression, give the pattern to RegExp() as a string.

Write the pattern as a raw string, with an r before the quotes, like r'\d+'.

In a raw string, a backslash \ is just a normal character, and patterns use a lot of backslashes.

The hasMatch() method returns true if the pattern is found somewhere in the string:

Example

void main() {
  RegExp digits = RegExp(r'\d');
  print(digits.hasMatch('Room 12'));
  print(digits.hasMatch('Kitchen'));
}
Try it Yourself »

Result:

true
false

The pattern \d means "one digit", so the first string has a match and the second does not.



Common Patterns

Here are some of the most used parts of a pattern:

PatternMatches
\dOne digit (0 to 9)
\wOne letter, digit or underscore
\sOne space, tab or new line
.Any one character (except a new line)
[abc]One of the characters a, b or c
+The part before it, one or more times
*The part before it, zero or more times
{3}The part before it, exactly 3 times
^The start of the string
$The end of the string

With ^ and $, the whole string must match the pattern.

This example checks that a PIN code has exactly 4 digits:

Example

void main() {
  RegExp pin = RegExp(r'^\d{4}$');
  print(pin.hasMatch('1234'));
  print(pin.hasMatch('12345'));
  print(pin.hasMatch('12a4'));
}
Try it Yourself »

Result:

true
false
false

To ignore upper and lower case, add caseSensitive: false:

Example

void main() {
  RegExp cat = RegExp(r'cat', caseSensitive: false);
  print(cat.hasMatch('My CAT is black'));
}
Try it Yourself »

Result:

true

Find Matches

The firstMatch() method returns the first match, or null if there is no match.

The group(0) method of a match returns the text that matched:

Example

void main() {
  RegExp number = RegExp(r'\d+');
  RegExpMatch? match = number.firstMatch('Order 45 has 3 items');
  if (match != null) {
    print(match.group(0));
    print(match.start);
  }
}
Try it Yourself »

Result:

45
6

match.start is the index where the match begins.

The allMatches() method finds every match in the string:

Example

void main() {
  RegExp number = RegExp(r'\d+');
  String text = 'Tom scored 12, Anna scored 19 and Ben scored 7';
  for (RegExpMatch match in number.allMatches(text)) {
    print(match.group(0));
  }
}
Try it Yourself »

Result:

12
19
7

You can also use map() to get all the matched texts as a list:

Example

void main() {
  RegExp word = RegExp(r'\w+');
  String text = 'red, green, blue';
  List<String> colors = word.allMatches(text).map((m) => m.group(0)!).toList();
  print(colors);
}
Try it Yourself »

Result:

[red, green, blue]

Groups

Parentheses () in a pattern make a group.

A group lets you get one part of the match.

group(1) is the text of the first group, group(2) is the second, and so on:

Example

void main() {
  RegExp datePattern = RegExp(r'(\d{4})-(\d{2})-(\d{2})');
  RegExpMatch? match = datePattern.firstMatch('The party is on 2026-12-24.');
  if (match != null) {
    print('Year: ${match.group(1)}');
    print('Month: ${match.group(2)}');
    print('Day: ${match.group(3)}');
  }
}
Try it Yourself »

Result:

Year: 2026
Month: 12
Day: 24

You can also give a group a name with (?<name>...), and read it with namedGroup():

Example

void main() {
  RegExp email = RegExp(r'(?<user>\w+)@(?<domain>[\w.]+)');
  RegExpMatch? match = email.firstMatch('Write to anna@example.com today');
  if (match != null) {
    print(match.namedGroup('user'));
    print(match.namedGroup('domain'));
  }
}
Try it Yourself »

Result:

anna
example.com

Replace Text

The string method replaceAll() also works with a RegExp.

It replaces every match with a new text:

Example

void main() {
  String phone = 'Call 555-123-4567 now';
  String hidden = phone.replaceAll(RegExp(r'\d'), '*');
  print(hidden);

  String messy = 'Too    many     spaces';
  print(messy.replaceAll(RegExp(r'\s+'), ' '));
}
Try it Yourself »

Result:

Call ***-***-**** now
Too many spaces

Other string methods that accept a RegExp are split(), contains() and replaceFirst():

Example

void main() {
  String fruits = 'apple, banana;cherry  kiwi';
  print(fruits.split(RegExp(r'[,;\s]+')));
  print(fruits.contains(RegExp(r'\d')));
}
Try it Yourself »

Result:

[apple, banana, cherry, kiwi]
false


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.