Try it yourself with our free Regex Tester tool — runs entirely in your browser, no signup needed.

How to Use regex to replace in Dart

How to use regex to replace in Dart

Regular expressions (regex) are a powerful tool for text manipulation, and Dart provides a robust API for working with them. In this guide, we'll explore how to use regex to replace text in Dart, covering the basics, common edge cases, and performance tips.

Quick Example

Here's a minimal example that replaces all occurrences of a pattern in a string:

import 'package:dart:core';

void main() {
  String input = 'Hello, world!';
  String pattern = 'world';
  String replacement = 'Dart';

  String output = input.replaceAll(RegExp(pattern), replacement);
  print(output); // Output: Hello, Dart!
}

This code uses the replaceAll method to replace all occurrences of the pattern 'world' with the replacement string 'Dart'.

Step-by-Step Breakdown

Let's walk through the code line by line:

  1. import 'package:dart:core';: We import the dart:core library, which provides the RegExp class used for regex operations.
  2. String input = 'Hello, world!';: We define the input string containing the text to be manipulated.
  3. String pattern = 'world';: We define the pattern to be replaced as a string.
  4. String replacement = 'Dart';: We define the replacement string.
  5. String output = input.replaceAll(RegExp(pattern), replacement);: We use the replaceAll method to replace all occurrences of the pattern in the input string. The RegExp constructor creates a regex object from the pattern string.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/Null Input

void main() {
  String input = null;
  String pattern = 'world';
  String replacement = 'Dart';

  try {
    String output = input.replaceAll(RegExp(pattern), replacement);
  } on TypeError catch (e) {
    print('Error: Input is null');
  }
}

In this case, we check for null input and handle the TypeError exception that would be thrown.

Invalid Input

void main() {
  String input = 'Hello, world!';
  String pattern = '[invalid regex]'; // invalid regex pattern
  String replacement = 'Dart';

  try {
    String output = input.replaceAll(RegExp(pattern), replacement);
  } on RegExpException catch (e) {
    print('Error: Invalid regex pattern');
  }
}

Here, we catch the RegExpException that would be thrown for an invalid regex pattern.

Large Input

void main() {
  String input = 'a'.repeat(1000000); // large input string
  String pattern = 'a';
  String replacement = 'b';

  String output = input.replaceAll(RegExp(pattern), replacement);
  print(output);
}

Dart's regex engine is designed to handle large input strings efficiently. However, for extremely large inputs, you may want to consider using a streaming approach or a specialized library.

Unicode/Special Characters

void main() {
  String input = 'Hëllo, wørld!';
  String pattern = 'wørld';
  String replacement = 'Dart';

  String output = input.replaceAll(RegExp(pattern, unicode: true), replacement);
  print(output);
}

To handle Unicode characters, we pass the unicode: true parameter to the RegExp constructor.

Common Mistakes

Here are some common mistakes developers make when using regex to replace in Dart:

Mistake 1: Not Escaping Special Characters

void main() {
  String input = 'Hello, world!';
  String pattern = '.'; // unescaped special character
  String replacement = 'Dart';

  String output = input.replaceAll(RegExp(pattern), replacement);
  print(output); // incorrect output
}

Corrected Code

void main() {
  String input = 'Hello, world!';
  String pattern = '\\.'; // escaped special character
  String replacement = 'Dart';

  String output = input.replaceAll(RegExp(pattern), replacement);
  print(output);
}

Mistake 2: Not Handling Null Input

void main() {
  String input = null;
  String pattern = 'world';
  String replacement = 'Dart';

  String output = input.replaceAll(RegExp(pattern), replacement); // TypeError
}

Corrected Code

void main() {
  String input = null;
  String pattern = 'world';
  String replacement = 'Dart';

  if (input != null) {
    String output = input.replaceAll(RegExp(pattern), replacement);
    print(output);
  } else {
    print('Error: Input is null');
  }
}

Mistake 3: Not Validating Regex Patterns

void main() {
  String input = 'Hello, world!';
  String pattern = '[invalid regex]'; // invalid regex pattern
  String replacement = 'Dart';

  String output = input.replaceAll(RegExp(pattern), replacement); // RegExpException
}

Corrected Code

void main() {
  String input = 'Hello, world!';
  String pattern = '[invalid regex]'; // invalid regex pattern
  String replacement = 'Dart';

  try {
    String output = input.replaceAll(RegExp(pattern), replacement);
    print(output);
  } on RegExpException catch (e) {
    print('Error: Invalid regex pattern');
  }
}

Performance Tips

Here are some practical performance tips for using regex to replace in Dart:

  1. Use efficient regex patterns: Avoid using overly complex patterns that can slow down the regex engine.
  2. Use caching: If you're performing multiple replacements with the same pattern, consider caching the compiled regex object.
  3. Use streaming: For extremely large inputs, consider using a streaming approach to avoid loading the entire input into memory.

FAQ

Q: What is the difference between replaceAll and replaceFirst?

A: replaceAll replaces all occurrences of the pattern, while replaceFirst replaces only the first occurrence.

Q: Can I use regex to replace in a StringBuffer?

A: Yes, you can use the replaceAll method on a StringBuffer object.

Q: How do I handle Unicode characters in regex patterns?

A: Pass the unicode: true parameter to the RegExp constructor.

Q: Can I use regex to replace in a List<String>?

A: Yes, you can use the map method to apply the replacement to each string in the list.

Q: How do I optimize regex performance in Dart?

A: Use efficient regex patterns, caching, and streaming approaches to improve performance.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp