国际电话号码的 Ruby 正则表达式,同时排除特定国家/地区代码

时间:2021-06-16 17:08:31

标签: regex ruby

我正在尝试创建一个正则表达式来授权表单中的国际电话号码,同时排除来自法国的电话号码(即以“+33”开头,因为我为这种情况创建了一个特定的正则表达式)。
此正则表达式应捕获以“+”开头的电话号码,后跟国家/地区代码(1 到 4 位数字)和 4 到 9 位数字,没有空格/破折号/点。

我环顾四周,想出了以下一个,其中包括所有国际电话号码:

(\(?\+[1-9]{1,4}\)?([0-9]{4,11})?)

我想用...排除法语数字

[^+33]

但我找不到将它与我当前的正则表达式结合的方法。

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

在开始时使用负前瞻

(?!^\+33)(\(?\+[1-9]{1,4}\)?([0-9]{4,11}) ?)

(?!^+33) 如果不是以 +33 开头则为真

答案 1 :(得分:1)

<块引用>

此正则表达式应捕获以“+”开头的电话号码,后跟国家/地区代码(1 到 4 位数字)和 4 到 9 位数字,不包含空格/破折号/点。

使用

\A(?!\+33)\+\d{1,3}\d{4,9}\z

regex proof

说明

--------------------------------------------------------------------------------
  \A                       the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    \+                       '+'
--------------------------------------------------------------------------------
    33                       '33'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  \+                       '+'
--------------------------------------------------------------------------------
  \d{1,3}                  digits (0-9) (between 1 and 3 times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \d{4,9}                  digits (0-9) (between 4 and 9 times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  \z                       the end of the string