Python -re

http://www.tutorialspoint.com/python/python_reg_expressions.htm

  • 匹配所有十进制数字
phone = '400-820-8377'
num = re.sub(r'\D', "", phone)  # 提取所有数字(因为把匹配到的非数字替换成空了)
# out: '4008208377'

num = re.sub(r'\d', "", phone)  # 提取所有非数字(因为把匹配到的数字替换成空了)
# '--'
  • 取括号中的内容
string = 'abe(ac)ad)'
p1 = re.compile(r'[(](.*?)[)]', re.S)  #最小匹配
p2 = re.compile(r'[(](.*)[)]', re.S)   #贪婪匹配
print(re.findall(p1, string))
print(re.findall(p2, string))
# 输出
['ac']
['ac)ad']

  • 列表快速去除空元素 (filter)
your_list = list(filter(None, your_list))  # 去掉空元素

猜你喜欢

转载自blog.csdn.net/weixin_34075268/article/details/90985638