Dart String Manipulations: Strings Pattern Matching

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, you can perform pattern matching on strings using regular expressions (RegExp). Here are some common operations for pattern matching:
1. Testing if a String Matches a Pattern:
You can use the hasMatch method of the RegExp class to check if a string matches a particular pattern:
void main() {
String text = "Dart is a powerful language.";
RegExp pattern = RegExp(r'\bDart\b');
if (pattern.hasMatch(text)) {
print("The text contains the word 'Dart'.");
} else {
print("The text does not contain the word 'Dart'.");
}
}
2. Finding Matches in a String:
The allMatches method returns an iterable of RegExpMatch objects representing all matches of the pattern in the given string:
void main() {
String text = "Dart is a Dart language.";
RegExp pattern = RegExp(r'\bDart\b');
Iterable<RegExpMatch> matches = pattern.allMatches(text);
for (RegExpMatch match in matches) {
print("Match found at index ${match.start}: ${match.group(0)}");
}
}
3. Extracting Captured Groups:
If your pattern contains capturing groups, you can extract the matched groups using the group method of the RegExpMatch object:
void main() {
String text = "John Doe, Jane Smith";
RegExp pattern = RegExp(r'(\w+) (\w+)');
Iterable<RegExpMatch> matches = pattern.allMatches(text);
for (RegExpMatch match in matches) {
String firstName = match.group(1);
String lastName = match.group(2);
print("First Name: $firstName, Last Name: $lastName");
}
}
4. Replacing Matches in a String:
Use the replaceAll method to replace all occurrences of the pattern with a specified string:
void main() {
String text = "Dart is a Dart language.";
RegExp pattern = RegExp(r'\bDart\b');
String replacedText = text.replaceAll(pattern, 'Flutter');
print("After replacement: $replacedText");
}
These examples cover some basic string pattern matching operations in Dart. Depending on your specific requirements, you might need more complex patterns or additional features provided by regular expressions. Feel free to ask if you have a particular use case or need more detailed examples!




