Regex电话号码实时格式化

Regex phone number live formatting

本文关键字:格式化 实时 电话号码 Regex      更新时间:2023-09-26

在AngularJS中,我需要在输入电话号码时对其进行格式化。我不想使用任何库,因为这应该是直接的。

我需要的格式是:99 99 99 99 99
var phone = tel.replace(/'D*('d{2})'D*('d{2})'D*('d{2})'D*('d{2})'D*('d{2})'D*/, '$1 $2 $3 $4 $5');

但是这只在我的数字完全输入后才格式化。当数字尚未完成时,如何使此正则表达式工作?

然后我试了这个:

var phone = tel.replace(/'D*('d{2})'D*('d{0,2})?'D*('d{0,2})?'D*('d{0,2})?'D*('d{0,2})?'D*/, '$1 $2 $3 $4 $5');

但这显然是添加了不必要的空格

你说你希望它是"直接的",但你人为地限制了问题(通过强迫解决方案只有正则表达式),而纯正则表达式实际上是一个糟糕的解决方案。

为什么?因为您的问题涉及有条件地向输出添加新字符(空格),这些字符可能不会出现在输入中,但不应该总是添加- .replace()不具备处理此问题的能力。

你最好结合使用regex和其他JavaScript来处理条件格式:

// Get only the digits from the string
var phoneDigits = tel.replace(/'D/g, "");
// Join together the first up-to-5 pairs of digits with spaces,
// allowing for a singleton if the number of digits is odd.
var phone = (phoneDigits.match(/'d'd?/g) || []).slice(0,5).join(" ");

(|| []位避免了没有数字时匹配返回null的情况)

您可以尝试层叠样式的模式。

var phone = tel.replace(/'D*(?:('d{2})'D*(?:('d{2})'D*(?:('d{2})'D*(?:('d{2})'D*(?:('d{2})'D*)?)?)?)?)?/, '$1 $2 $3 $4 $5');

 'D* 
 (?:
      ( 'd{2} )                     # (1)
      'D* 
      (?:
           ( 'd{2} )                     # (2)
           'D* 
           (?:
                ( 'd{2} )                     # (3)
                'D* 
                (?:
                     ( 'd{2} )                     # (4)
                     'D* 
                     (?:
                          ( 'd{2} )                     # (5)
                          'D* 
                     )?
                )?
           )?
      )?
 )?