Python新手请教正则表达式的问题

print(re.findall("(as)|3",“3as”)) 为什么执行结果是 [’’, ‘as’] 怎么会出现一个空字符串呢,谢谢
Python新手请教正则表达式的问题

2 回复

正则表达式确实有点绕,我来给你讲点实用的。

匹配邮箱的正则可以这样写:

import re

pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
email = "test@example.com"

if re.match(pattern, email):
    print("邮箱格式正确")

匹配手机号(中国):

pattern = r'^1[3-9]\d{9}$'
phone = "13800138000"

if re.match(pattern, phone):
    print("手机号格式正确")

提取文本中的数字:

text = "价格是199元,折扣后150.5元"
numbers = re.findall(r'\d+\.?\d*', text)
print(numbers)  # ['199', '150.5']

几个常用符号:

  • . 匹配任意字符(除了换行)
  • \d 匹配数字
  • \w 匹配字母、数字、下划线
  • * 匹配0次或多次
  • + 匹配1次或多次
  • ? 匹配0次或1次
  • {n} 匹配n次
  • {n,m} 匹配n到m次

建议先用在线工具测试正则,比如 regex101.com,确认没问题再写到代码里。

正则多练就会了。


https://docs.python.org/2/library/re.html#re.findall

If one or more groups are present in the pattern, return a list of groups;

如果有分组则返回分组,你这里有分组,但‘ 3 ’没有分组,所以匹配到了 3,仍返回了一个空

回到顶部