【问题标题】:Which is better method to declare regex pattern?声明正则表达式模式的更好方法是什么?
【发布时间】:2015-06-05 03:09:16
【问题描述】:

我有 python 类文件。

import re

regex = {
    'a1': re.compile('(\d+)'),
}
# or A1_REGEX = re.compile('(\d+)')

class A1():
    def toview(self, mystring):
        data = regex['a1'].search(mystring)
        if data:
            ......

import re
class A1():
    a1 = re.compile('(\d+)')
    def toView(self, mystring):
        data = a1.search(mystring)
        if data:
            .......

请任何人告诉,哪一个更好,更准确。 ? 哪一个是python标准编码/PEP8标准? 在这种情况下,正则表达式使用是否有任何时间消耗或内存使用情况 可以考虑 ? 请在此添加您的意见或 cmets。 感谢您宝贵的 cmets。!

【问题讨论】:

  • 请注意,在您的类方法中,第一个参数始终是对类实例的引用,通常称为 self

标签: python python-2.7 python-3.x scrapy pep8


【解决方案1】:

第二个选项对我来说更具可读性,因为该类只引用自身,而不是它周围的任何东西。就像在Zen of Python

可读性很重要。

至于性能,不会有太大的差别,即使正则表达式的复杂度增加。 regex module 负责缓存模式,因此只会编译一次:

传递给re.match()re.search()re.compile() 的最新模式的编译版本被缓存,因此一次只使用几个正则表达式的程序无需担心编译正则表达式。


编辑

这样会更好:

import re

class A1():
   def __init__(self):
       self.preg = re.compile(r'(\d+)')
   def toView(self, mystring):
       data = self.preg.search(mystring)
       if data:
           pass

这样,继承就干净多了:

class B1(A1):
    def check(self, data):
        return self.preg.match(data)

【讨论】:

  • 如果基类扩展为其他子类。到时候,是不是可行的解决方案。 ?
猜你喜欢
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
相关资源
最近更新 更多