close

how to use regex in dart?

RegEx in Dart work same as some other language. RegEx are the piece of Dart Code library,

Essential

  • How to make RegEx Strings?
  • Practice and Validate RegEx
  • RegEx Search Engine

A RegExp class call be initialised like after:

RegExp(r'<your reguler expression>');

Validating Text:

RegExp calenderDate = RegExp(r'^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$');  //mm/dd/yyyy
    calenderDate.hasMatch("12/12/2020"); //true
    calenderDate.hasMatch("20/12/2020"); //false

Extracting Text:

RegExp exp = new RegExp(r"(\w+)");
// Find the Card number in string 
String str = "Parse my string";
//use func firstMatch to get first matching String 
Iterable<Match> matches = exp.allMatches(str);


if (matches == null) {
    print("No match");
} else {
    
    // group(0) => full matched text
    // if regex had groups. groups can be extracted 
    // using group(1), group(2)...
    final matchedText = matches.elementAt(1).group(0);
    print(matchedText); // my
}

Thanks for being with us on a Flutter Journey!!!

Leave a Comment