【问题标题】:Ruby regex for international phone numbers while excluding a specific country code国际电话号码的 Ruby 正则表达式,但不包括特定国家/地区代码
【发布时间】:2021-09-01 13:03:18
【问题描述】:

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

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

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

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

[^+33]

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

提前感谢您的帮助。

【问题讨论】:

    标签: regex ruby


    【解决方案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
    

    【讨论】:

    • 非常感谢您快速详细的回答,它的工作就像一个魅力!
    【解决方案2】:

    在开头使用负前瞻

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

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

    【讨论】:

    • 非常感谢您对否定前瞻的超快速回答和解释。
    猜你喜欢
    • 1970-01-01
    • 2022-07-22
    • 2019-05-30
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-12-15
    相关资源
    最近更新 更多