Skip to main content

Command Palette

Search for a command to run...

Dart String Manipulations: Strings RegExp

Published
2 min readView as Markdown
Dart String Manipulations: Strings RegExp
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, regular expressions (RegExp) can be used for powerful string manipulations. Dart provides the RegExp class to work with regular expressions, and you can use it with various string manipulation methods. Here's a brief overview of some common string manipulations using regular expressions in Dart:

  1. Creating a RegExp: You can create a RegExp using the RegExp constructor. For example:

     RegExp myRegExp = RegExp(r'\d+');
    

    In this example, the regular expression \d+ matches one or more digits.

  2. Testing if a String Matches a RegExp: You can use the hasMatch method of the RegExp class to check if a string matches the regular expression:

     bool isMatch = myRegExp.hasMatch('12345');
     print(isMatch);  // true
    
  3. Finding Matches in a String: The allMatches method returns an iterable of Match objects for all matches in the string:

     Iterable<Match> matches = myRegExp.allMatches('12345 6789');
     for (Match match in matches) {
       print(match.group(0));  // prints each matched substring
     }
    
  4. Replacing Matches in a String: You can use the replaceAll method to replace all occurrences of the regular expression in a string:

     String replacedString = 'abc123'.replaceAll(myRegExp, 'X');
     print(replacedString);  // 'abcX'
    
  5. Extracting Substrings using Groups: You can use capturing groups in your regular expression to extract specific parts of the matched string:

     RegExp myRegExpWithGroups = RegExp(r'(\d+)-(\d+)');
     Match match = myRegExpWithGroups.firstMatch('123-456');
     print(match.group(1));  // '123'
     print(match.group(2));  // '456'
    

These are just basic examples, and regular expressions can be as simple or as complex as needed for your specific use case. Make sure to check the official Dart documentation on RegExp for more details and options.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.