首页 > 解决方案 > 如何在python中返回re.search()的字符串表示

问题描述

我知道 python 方法中的 [re.search(pattns,text)][1] 采用正则表达式模式和字符串,并在字符串中搜索该模式。如果搜索成功,则 search() 返回匹配对象,否则返回 None。

然而,我的问题是,我试图使用 OOP(类)来实现这一点,我想返回匹配结果的字符串表示形式,无论是真还是无或任何其他形式的表示(可读)而不是0x7f30d0a81440 处的 <__main__.Expression 实例>下面是两个示例类:Student 和 Epression。使用__str__(self)__的那个工作正常,但我不知道如何获得re.search()的表示函数。请有人帮助我。

import re   

class Expression:
    def __init__(self,patterns,text):

        self.patterns = patterns
        self.text = text


    def __bool__(self):
    # i want to get a readable representation from here
        for pattern in self.patterns:
           result = re.search(pattern,self.text)
           return result



 patterns = ['term1','term2','23','ghghg']
 text = 'This is a string with term1 23 not ghghg the other'

 reg = Expression(patterns,text)
 print(reg)


 class Student:

    def __init__(self, name):

       self.name = name


   def __str__(self):
    # string representation here works fine
        result = self.name 
        return result

 # Usage:

  s1 = Student('john')
  print(s1)


 [1]: https://developers.google.com/edu/python/regular-expressions

标签: pythonregex

解决方案


的输出 re.search 返回一个匹配对象。它告诉您正则表达式是否与字符串匹配。

您应该识别组以从匹配中检索字符串,如下所示:

if result: 
    return result.group(0)

return result用上面的代码片段替换您的代码。

如果您不确定如何group工作,以下是文档中的示例:

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") 
>>> m.group(0) # The entire match 
'Isaac Newton' 
>>> m.group(1) # The first parenthesized subgroup. 
'Isaac' 
>>> m.group(2) # The second parenthesized subgroup. 
'Newton' 
>>> m.group(1, 2) # Multiple arguments give us a tuple. 
('Isaac', 'Newton')

推荐阅读