python - 如何在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
解决方案
的输出 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')
推荐阅读
- reactjs - Reactjs 中的 Crud 更新操作不起作用
- python - 从 google book api 获取缩略图到 python 变量
- reactjs - 您可以将 React useState 状态对象传递给使用 Tailwind 和 twin.macro 的样式化组件吗?
- c# - 尝试修复此 dataGridView 列 Autosizemode 问题
- reactjs - 单击 React 中的按钮后创建 PDF 文档
- angular - 如何使用 0 值的角度 DatePipe?
- kivy - Kivy:如何摆脱 TextInput 中奇怪的阴影外观?
- wcf - 签署认证请求
- r - 在 Shiny 中,是否可以提取与给定值不同的输入值(即,将百分比转换为小数)?
- html - 如何在 boxlist 中显示 WTforms 选项?