如何匹配Python中的单词,如果不存在,如何引发异常?
我正在尝试匹配一个单词“None”,如果没有找到,我需要引发异常。我已经尝试了下面的python代码如何匹配Python中的单词,如果不存在,如何引发异常?,python,python-2.7,Python,Python 2.7,我正在尝试匹配一个单词“None”,如果没有找到,我需要引发异常。我已经尝试了下面的python代码 import re text = "None" match1 = re.match('.*None', text) mat1 = ['None'] if match1 == mat1: print "match found" if match1 != mat1: raise Exception('Not fou
import re
text = "None"
match1 = re.match('.*None', text)
mat1 = ['None']
if match1 == mat1:
print "match found"
if match1 != mat1:
raise Exception('Not found...')
但我总是得到以下错误:
C:\Users\test\Desktop>python test.py
Traceback (most recent call last):
File "test.py", line 25, in <module>
raise Exception('Not found...')
Exception: Not found...
C:\Users\test\Desktop>
C:\Users\test\Desktop>python test.py
回溯(最近一次呼叫最后一次):
文件“test.py”,第25行,在
引发异常('未找到…')
异常:找不到。。。
C:\Users\test\Desktop>
有人能帮我解决这个问题吗?
re.match
返回匹配对象而不是列表
import re
text = "None"
match1 = re.match('.*None', text)
if not match1:
raise Exception('Not found...')
print(match1.group(0))
使用正则表达式时,
match
方法的结果是一个match对象,您可以使用该对象执行其他方法。您甚至可以在if-else
条件中直接比较它,以检查是否执行了任何匹配
如果您确实想使用RE,正确的方法是:
if match1:
print 'Match found'
else:
raise Exception('Not found...')
检查句子中是否存在None
可能更简单的方法是使用in
运算符:
if 'None' in text:
print 'Found None'
else:
raise Exception('None not found')
提供简单的示例,帮助您理解如何使用此模块。问题在于假定返回值的方式
re.match('.*None',text)
来自文档
重新匹配(模式、字符串、标志=0)
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的MatchObject
实例。如果字符串与模式不匹配,则返回None
;请注意,这与零长度匹配不同
因此
如果match1==mat1:
始终为false,因为mat1=['None']
因此您总是会得到异常。您绝对需要使用regex吗
这似乎更容易:
if "None" not in text:
raise Exception('Not found...')
当然,这只匹配字面上的“无”,而不是例如“无”。但你的正则表达式也是如此…@mirisval谢谢你的回答。它起作用了。但除此之外,its也会抛出以下错误:“C:\Users\test\Desktop>python test.py回溯(最后一次调用):文件“test.py”,第21行,在引发异常('Not found…')异常:Not found…C:\Users\test\Desktop>“抛出错误异常时,
text
中有什么内容?”?这是您想要引发的异常,因此可能是正确的行为。@mirisval我指的是以下错误“回溯(最近一次调用):文件“test.py”,第21行,in”。有没有一种方法可以修复这个错误?当然,您已经提出了错误,您需要捕获它,请参阅。如果你让它冒泡而没有抓住它,就会发生这种情况。