Regular Expressions in Dart

Our first program demonstrates the use of regular expressions in Dart. Here’s the full source code:

import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

void main() {
  // This tests whether a pattern matches a string.
  final match = RegExp(r'p([a-z]+)ch').hasMatch('peach');
  print(match);

  // For other regex tasks, you'll need to create a RegExp object.
  final r = RegExp(r'p([a-z]+)ch');

  // Many methods are available on these objects. Here's
  // a match test like we saw earlier.
  print(r.hasMatch('peach'));

  // This finds the match for the regex.
  print(r.stringMatch('peach punch'));

  // This finds the first match but returns the
  // start and end indexes for the match instead of the
  // matching text.
  final match2 = r.firstMatch('peach punch');
  print('idx: [${match2?.start}, ${match2?.end}]');

  // The groups in the regex pattern can be accessed
  // using the groups method on the match object.
  final match3 = r.firstMatch('peach punch');
  print(match3?.groups([0, 1]));

  // To find all matches in the input, use allMatches.
  final allMatches = r.allMatches('peach punch pinch');
  print(allMatches.map((m) => m.group(0)).toList());

  // Providing a non-negative integer as the second
  // argument to these functions will limit the number
  // of matches.
  final limitedMatches = r.allMatches('peach punch pinch').take(2);
  print(limitedMatches.map((m) => m.group(0)).toList());

  // Our examples above had string arguments. We can also provide
  // List<int> arguments (which is equivalent to []byte in Go).
  final utf8Encoder = Utf8Encoder();
  print(r.hasMatch(String.fromCharCodes(utf8Encoder.convert('peach'))));

  // The RegExp package can also be used to replace
  // subsets of strings with other values.
  print(r.stringMatch('a peach')?.replaceAll(r, '<fruit>'));

  // The replaceAllMapped variant allows you to transform matched
  // text with a given function.
  final input = utf8Encoder.convert('a peach');
  final output = r.allMatches(String.fromCharCodes(input))
      .map((match) => match.group(0)?.toUpperCase())
      .join();
  print(output);
}

To run the program, save it as regular_expressions.dart and use dart run:

$ dart run regular_expressions.dart
true
true
peach
idx: [0, 5]
[peach, ea]
[peach, punch, pinch]
[peach, punch]
true
<fruit>
PEACH

This example demonstrates various features of Dart’s regular expression support:

  1. Basic pattern matching using RegExp.hasMatch()
  2. Creating RegExp objects for more complex operations
  3. Finding matches and their positions in strings
  4. Accessing capturing groups
  5. Finding all matches in a string
  6. Limiting the number of matches
  7. Working with UTF-8 encoded data
  8. Replacing matched substrings
  9. Transforming matched substrings

For a complete reference on Dart regular expressions, check the RegExp class documentation in the Dart API.