社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python regex将括号限制为一次

Norman Y • 7 年前 • 2793 次点击  

我在python中遇到了一个问题,程序必须检查用户是否以有效格式输入电话号码,例如: (111)-111-1111 我用python正则表达式编写了这个程序 re.findall 但是,后来我意识到程序允许用户输入任意多的括号,例如: (((((111)-111-1111 而这仍然会作为一种有效的格式通过程序。 问题。是否有方法将括号的数目限制为 (111)-111-1111 ? 我的代码如下:

import re
number=input("Please enter phone number:  " )                    
x=re.findall('([(+*)]\d{3}[(+*)][a-]\d{3}[a-]\d{4})', number)
if (x):
    print("Perfect! Your format is valid: -->  " "'"+number+"'")
else:
    print("Not a valid format, please enter as (###)-###-####")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40889
文章 [ 3 ]  |  最新文章 7 年前
doubleo
Reply   •   1 楼
doubleo    7 年前

您可以使用下面的行:

x=re.findall('^\(\d{3}\)-\d{3}-\d{4}$', number)

这也检查开始和结束字符。

Pushpesh Kumar Rajwanshi
Reply   •   2 楼
Pushpesh Kumar Rajwanshi    7 年前

用于验证移动电话号码,如 (111)-111-1111 我不认为你需要像这样一个过于复杂和不正确的正则表达式 ([(+*)]\d{3}[(+*)][a-]\d{3}[a-]\d{4}) 即使你把起锚 ^ 和端锚 $ 它将验证以下手机号码是否有效,如果正确的话,

)111(a111a1111
*111+-111-1111

Check this demo to see how it allows invalid mobile numbers

用于验证这样的移动电话号码 (111)-111-1111 ,您可以使用以下正则表达式,

^\(\d{3}\)-\d{3}-\d{4}$

Demo for correctly validating mobile numbers

如果你想让我知道 (111)-111-1111 手机号码有效。

另外,对于验证文本,应该使用 match 功能而不是 findall 后者用于从文本中提取信息,前者用于匹配文本以获得有效性。

下面是一个示例python代码,它展示了如何验证移动电话号码,

import re

arr = ['(111)-111-1111','(((((111)-111-1111',')111(a111a1111','*111+-111-1111']

for s in arr:
 if (re.match(r'^\(\d{3}\)-\d{3}-\d{4}$', s)):
  print(s, ' --> is Valid mobile number')
 else:
  print(s, ' --> is Not Valid mobile number')

印刷品,

(111)-111-1111  --> is Valid mobile number
(((((111)-111-1111  --> is Not Valid mobile number
)111(a111a1111  --> is Not Valid mobile number
*111+-111-1111  --> is Not Valid mobile number
Allan
Reply   •   3 楼
Allan    7 年前

你很快就能让你的代码工作了。 您只需将样本调整为:

import re

number=input("Please enter phone number:  " )
x=re.match('^([(+*)]\d{3}[(+*)][a-]\d{3}[a-]\d{4})$', number)
if (x):
  print("Perfect! Your format is valid: -->  " "'"+number+"'")
else:
  print("Not a valid format, please enter as (###)-###-####")

在哪里,而不是使用 findall ,你使用 match 因为您正在检查这个数字是否与模式(regex)相关,而且您不想从中提取一些子信息。

你还需要添加锚( ^ , $ )在正则表达式中强制输入字符串开头或结尾不包含其他字符。

输出:

Please enter phone number:  '(111)-111-1111'
Perfect! Your format is valid: -->  '(111)-111-1111'
Please enter phone number:  '(((((111)-111-1111'
Not a valid format, please enter as (###)-###-#