Example #1
0
        public List <AntextStringItem> Analyze(string text)
        {
            List <AntextStringItem> foundItems = new List <AntextStringItem>();

            // Try to use libphonenumber
            PhoneNumberUtil         phoneUtils        = PhoneNumberUtil.GetInstance();
            List <PhoneNumberMatch> findNumbersResult = phoneUtils.FindNumbers(text, null, PhoneNumberUtil.Leniency.POSSIBLE, 100).ToList();

            foreach (PhoneNumberMatch phoneNumberMatch in findNumbersResult)
            {
                foundItems.Add(new AntextStringItem(AntextStringItemType.PhoneNumber, phoneNumberMatch.Start, phoneUtils.Format(phoneNumberMatch.Number, PhoneNumberFormat.INTERNATIONAL)));
            }

            // If nothing was found, try to use custom regex
            if (!foundItems.Any())
            {
                // Nothing was found, try use regex
                // This should match any sequence of numbers, separated by space or hypen, having 7-30 chars
                var matches = Regex.Matches(text, phoneRegexPattern);
                foreach (Match match in matches)
                {
                    // Replace spaces or hypens if any
                    string fix = match.Value.Replace(" ", "").Replace("-", "");

                    // If revised's string length match possible phone number length, try to fix it
                    if (fix.Length > 8 && fix.Length < 30)
                    {
                        PhoneNumber parsedPhone = phoneUtils.Parse(fix, defaultRegion);
                        foundItems.Add(new AntextStringItem(AntextStringItemType.PhoneNumber, match.Index, match.Value, (phoneUtils.Format(parsedPhone, PhoneNumberFormat.INTERNATIONAL))));
                    }
                }

                //if (matches.Success)
                //{
                //    foreach (Capture match in matches.Captures)
                //    {
                //        // Replace spaces or hypens if any
                //        string fix = match.Value.Replace(" ", "").Replace("-", "");

                //        // If revised's string length match possible phone number length, try to fix it
                //        if (fix.Length > 8 && fix.Length < 30)
                //        {
                //            PhoneNumber parsedPhone = phoneUtils.Parse(fix, defaultRegion);
                //            foundItems.Add(new AntextStringItem(AntextStringItemType.PhoneNumber, match.Index, match.Value, (phoneUtils.Format(parsedPhone, PhoneNumberFormat.INTERNATIONAL))));
                //        }
                //    }
                //}
            }


            return(foundItems);
        }