skip to Main Content

I’m trying to figure out how to detect if a given string contains a phone number in Dart, whether starting with a country code or zero. I have searched for various methods to see if a string contains a phone number but haven’t found any. The only search I’m getting is on how to validate a phone number in Dart.

The following is the code I’m currently using with no luck. I have tried a bunch of other stuffs but the following is the latest.

void detectPhoneNumber(String message){
  if(message.contains(RegExp(r'^(?:[+0]9)?[0-9]{10}$'))){
    print("A phone number was found!");
    return; 
  } 
  print("no luck!");
}

void main(){
  detectPhoneNumber("RG44NO7QR2 Confirmed. xxx sent to  Grace 0712345678 on 4/7/23 at 10:52 AM.  ");
}

2

Answers


  1. The regular expression you’re using in your detectPhoneNumber function is not correctly formatted to match a phone number.
    Also, you’re using the contains method, which checks if a string contains a substring, but it doesn’t support regular expressions.

    void detectPhoneNumber(String message) {
      RegExp phoneRegex = RegExp(r'^(?:[+0]9)?[0-9]{10}$');
    
      if (phoneRegex.hasMatch(message)) {
        print("A phone number was found!");
        return;
      }
    
      print("No luck!");
    }
    
    void main() {
      detectPhoneNumber("RG44NO7QR2 Confirmed. xxx sent to Grace 0712345678 on 4/7/23 at 10:52 AM.");
    }
    
    Login or Signup to reply.
  2. You can detect the String inside your Phone number via Regular Expression.

    bool containsPhoneNumber(String input) {
      // Regular expression pattern for a basic phone number
      final pattern = r'bd{3}[-.]?d{3}[-.]?d{4}b';
    
      // Create a regular expression object
      final regex = RegExp(pattern);
    
      // Check if the input matches the pattern
      return regex.hasMatch(input);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search