【问题标题】:How to return string representation of re.search() in python如何在python中返回re.search()的字符串表示
【发布时间】:2018-04-28 06:54:22
【问题描述】:

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

然而,我的问题是,我正在尝试使用 OOP(类)来实现这一点,我想返回匹配结果的字符串表示形式,无论是真还是无 或任何其他形式的表示(可读)不是这个 <__main__.expression instance at> 下面是两个示例类: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

【问题讨论】:

标签: python regex


【解决方案1】:

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

您应该像这样识别要从匹配中检索字符串的组:

if result: 
    return result.group(0)

将代码中的return result 替换为上面的代码sn-p。

如果您不确定 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')

【讨论】:

    【解决方案2】:

    首先,您的代码中有一个微妙的错误

    def __bool__(self):
        for pattern in self.patterns:
           result = re.search(pattern,self.text)
           return result
    

    当您在第一次迭代结束时返回搜索模式的结果时,其他模式将被忽略。

    你可能想要这样的东西:

    def __bool__(self):
        result = True
        for pattern in self.patterns:
           result = result or bool(re.search(pattern,self.text))
        return result
    

    关于表示,您可以使用.group(0)。这将返回匹配的字符串,而不是 re.Match obscur 表示。

    import re
    
    s = re.search(r"ab", "okokabuyuihiab")
    
    print(s.group(0))
    # "ab"
    

    当您使用模式列表时,也许可以使用:

    results = [re.search(pattern, seld.text) for pattern in self.patterns]
    representation = [r.group(0) for r in results if r else None]
    

    【讨论】:

      猜你喜欢
      • 2016-08-11
      • 1970-01-01
      • 2021-09-22
      • 2013-11-23
      • 2021-08-23
      • 2019-01-20
      • 2013-11-05
      • 1970-01-01
      • 2020-08-12
      相关资源
      最近更新 更多