Regular expressions are an indispensable tool in every programming language to search for matching patterns in strings. Dart has the RegExp
class from dart:core
, which uses the same syntax and semantics as JavaScript.
We use RegExp
in the following code (see using_regexp.dart
) to quickly determine whether a credit card number seems valid:
var visa = new RegExp(r"^(?:4[0-9]{12}(?:[0-9]{3})?)$"); var visa_in_text = new RegExp(r"\b4[0-9]{12}(?:[0-9]{3})?\b"); var input = "4457418557635128"; var text = "Does this text mention a VISA 4457418557635128 number?"; void main() { print(visa.pattern); // is there a visa pattern match in input? if (visa.hasMatch(input)) { print("Could be a VISA number"); } // does string input contain pattern visa? if (input.contains(visa)) { print("Could be a VISA number"); } // find all matches: var matches = visa_in_text.allMatches(text); for (var m in matches) { print(m.group(0)); } visa_in_text...