【发布时间】: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
【问题讨论】: