首页 > 解决方案 > flutter how to compare two different format phone numbers

问题描述

I am trying to find if two phone numbers are same or not (Two same phone number may not be in the same format, as +919998245345 is same as 9998245345 and 99982 45345)

标签: flutterdart

解决方案


For this, you can use contains() dart string method. I have marked the trailing statement as bold, cos, it applies on the String. Make sure you get the number in String format, or convert it to String and then perform the operation.

Alogrithm

  1. Convert the number to be compared to String, or get the number as String
  2. Remove all the white spaces using this code, your_phone_number_variable.replaceAll(new RegExp(r"\s+"), ""). So that every number should be having no white spaces in between for smooth operation
  3. Use contains() like this, number1.contains(number2)

Code

// this is a comparision between +919998245345 and other numbers
// you can play around and get what you want
void main() {
  var _inputPhone = "+919998245345";
  var _checkPhone = "9998245345";
  var _anotherCheck = "99982 45345";
  
  // checking that white space removal works or not
  print(_anotherCheck.replaceAll(new RegExp(r"\s+"), ""));
  
  // I have just removed the spaces from the number which had the white
  // space, you can store the value using this code for every data
  // for unknown data coming from server side or user side
  _anotherCheck = _anotherCheck.replaceAll(new RegExp(r"\s+"), "");
  if(_inputPhone.contains(_anotherCheck)){
    print('99982 45345 and +919998245345 are same');
  }
  
  if(_inputPhone.contains(_checkPhone)){
    print('9998245345 and +919998245345 are same');
  }
  
}

Output

9998245345
99982 45345 and +919998245345 are same
9998245345 and +919998245345 are same

推荐阅读