findPhoneNumbers method

List<String> findPhoneNumbers(
  1. String text
)

The findPhoneNumbers function uses a regular expression (phoneRegExp) to find phone numbers in the provided text. It can match phone numbers in various common formats like "123-456-7890," "(555) 555-5555," "987.654.3210," and "888 888 8888."

Implementation

List<String> findPhoneNumbers(String text) {
  final RegExp phoneRegExp = RegExp(
    r'(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)[-.\s]??\d{3}[-.\s]??\d{4})',
    caseSensitive: false,
    multiLine: true,
  );

  final Iterable<Match> matches = phoneRegExp.allMatches(text);

  final List<String> phoneNumbers = [];

  for (Match match in matches) {
    phoneNumbers.add(match.group(0)!);
  }

  return phoneNumbers;
}