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
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.You can detect the String inside your Phone number via Regular Expression.