您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python中简洁地级联多个正则表达式语句

如何在Python中简洁地级联多个正则表达式语句

9月中的类似问题:您如何将这种正则表达式习语从Perl转换为Python?

在模块中使用全局变量可能不是最好的方法,但可以将其转换为类:

import re

class Re(object):
  def __init__(self):
    self.last_match = None
  def match(self,pattern,text):
    self.last_match = re.match(pattern,text)
    return self.last_match
  def search(self,pattern,text):
    self.last_match = re.search(pattern,text)
    return self.last_match

gre = Re()
if gre.match(r'foo',text):
  # do something with gre.last_match
elif gre.match(r'bar',text):
  # do something with gre.last_match
else:
  # do something else
python 2022/1/1 18:52:12 有303人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶