US Office

1176 Shadeville Rd, Crawfordville Florida 32327, USA

 +1 (850) 780-1313

India Office

Office No 405, Kabir Shilp, Opp. Kansar Hotel, Opp. Landmark, Kudasan, Gandhinagar, Gujarat 382421

[email protected]

How to Use RegEx In Dart?

How to Use RegEx In Dart

How to Use RegEx In Dart?

RegEx in Dart works the same as any other language. RegEx is part of the Dart code library, implemented in RegExp Class. So in this article, we will go through how to use RegEx in Dart.

How to Use RegEx in Dart?

We need to try to include options in the raw expression string while you already have it as parameters to RegEx ( /i for case insensitivity is declared as caseSensitive: false).

// Removed /i at the end
// Removed / in front - Thanks to Günter for warning
RegExp regExp = new RegExp(
  r"^WS{1,2}:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:56789",
  caseSensitive: false,
  multiLine: false,
);
print("allMatches : "+regExp.allMatches("WS://127.0.0.1:56789").toString());
print("firstMatch : "+regExp.firstMatch("WS://127.0.0.1:56789").toString());
print("hasMatch : "+regExp.hasMatch("WS://127.0.0.1:56789").toString());
print("stringMatch : "+regExp.stringMatch("WS://127.0.0.1:56789").toString());

So this will give:

allMatches : (Instance of '_MatchImplementation')
firstMatch : Instance of '_MatchImplementation'
hasMatch : true
stringMatch : WS://127.0.0.1:56789

So Regex in dart works much like other languages. You use the RegExp Class to define a matching pattern.

So now, use hasMatch() to test the pattern on a string.

Examples for the same

Alphanumeric:

final alphanumeric = RegExp(r'^[a-zA-Z0-9]+$');
alphanumeric.hasMatch('abc123');  // true
alphanumeric.hasMatch('abc123%'); // false

Hex Colors:

RegExp hexColor = RegExp(r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$');
hexColor.hasMatch('#3b5');     // true
hexColor.hasMatch('#FF7723');  // true
hexColor.hasMatch('#000000z'); // false

So now, Extracting the Text like this:

final myString = '25F8..25FF    ; Common # Sm   [8] UPPER LEFT TRIANGLE';

// find a variable length hex value at the beginning of the line
final regexp = RegExp(r'^[0-9a-fA-F]+'); 

// find the first match though you could also do `allMatches`
final match = regexp.firstMatch(myString);

// group(0) is the full matched text
// if your regex had groups (using parentheses) then you could get the 
// text from them by using group(1), group(2), etc.
final matchedText = match.group(0);  // 25F8

There are some more examples here.

Conclusion:

Thanks for being with us on a Flutter Journey !!! Stay Connected 🙂

So in this article, we have been through how to use RegEx in Dart.

Keep Learning !!! Keep Fluttering !!!

So let us know if you are still confused about Flutter Development 🙂 We would love to assist you.

Flutter Agency is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

Post a Comment