How to use Regular expression (regex) in Flutter

Regular expressions are a powerful tool for pattern matching and text manipulation in programming. Flutter provides support for regex through the dart:core library. To use regex in Flutter, you need to import this library:

import 'dart:core';

Once you have the dart:core library imported, you can use the RegExp class to create a regular expression object. Here are some examples of how to use regular expressions in Flutter:

  • Matching a pattern in a string:
RegExp pattern = RegExp(r'hello');
String text = 'Hello, World!';
bool isMatch = pattern.hasMatch(text);
print(isMatch); // Output: false

In this example, we create a regular expression pattern that matches the string “hello”. We then use the hasMatch method of the RegExp class to check if the pattern matches the text “Hello, World!”. Since the pattern is case sensitive, the method returns false.

  • Extracting substrings using capturing groups:
RegExp pattern = RegExp(r'(\d{3})-(\d{3})-(\d{4})');
String text = 'My phone number is 123-456-7890.';
Iterable<Match> matches = pattern.allMatches(text);
for (Match match in matches) {
  String phoneNumber = match.group(0);
  String areaCode = match.group(1);
  String prefix = match.group(2);
  String lineNumber = match.group(3);
  print(phoneNumber); // Output: 123-456-7890
  print(areaCode); // Output: 123
  print(prefix); // Output: 456
  print(lineNumber); // Output: 7890
}

In this example, we create a regular expression pattern that matches a phone number in the format of XXX-XXX-XXXX, where X is a digit. We then use the allMatches method of the RegExp class to find all matches of the pattern in the text “My phone number is 123-456-7890.”. For each match, we extract the entire phone number and its components (area code, prefix, and line number) using capturing groups.

  • Replacing substrings using a regular expression:
RegExp pattern = RegExp(r'fox');
String text = 'The quick brown fox jumped over the lazy dog.';
String replacement = 'cat';
String replacedText = text.replaceAll(pattern, replacement);
print(replacedText); // Output: The quick brown cat jumped over the lazy dog.

In this example, we create a regular expression pattern that matches the string “fox”. We then use the replaceAll method of the String class to replace all occurrences of the pattern in the text “The quick brown fox jumped over the lazy dog.” with the string “cat”.

These are just a few examples of how to use regular expressions in Flutter. There are many more options available, such as using different modifiers, using lookarounds, and more. You can find more information on regular expressions and their capabilities in the Dart language documentation.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *