在python中,如何“如果finditer(...)没有匹配项”?
问题内容:
当finditer()找不到任何东西时,我想做些什么。
import re
pattern = "1"
string = "abc"
matched_iter = re.finditer(pattern, string)
# <if matched_iter is empty (no matched found>.
# do something.
# else
for m in matched_iter:
print m.group()
我能想到的最好的办法是手动跟踪找到的内容:
mi_no_find = re.finditer(r'\w+',"$$%%%%") # not matching.
found = False
for m in mi_no_find:
print m.group()
found = True
if not found:
print "Nothing found"
不回答的相关文章:
- 计算finditer匹配项:正则表达式匹配项的数量(我不需要计算,我只需要知道是否没有匹配项即可)。
- finditer vs match:使用re.finditer和re.match时的行为不同(说总是必须遍历finditer返回的迭代器)
[edit]
-我对枚举或计数总输出没有兴趣。只有找到了,否则找不到动作。
-我知道我可以将finditer放入列表中,但这对于大字符串而言效率不高。一个目标是降低内存利用率。
问题答案:
更新了04/10/2020
使用re.search(pattern, string)
来检查,如果存在模式。
pattern = "1"
string = "abc"
if re.search(pattern, string) is None:
print('do this because nothing was found')
返回值:
do this because nothing was found
如果你想 遍历返回 ,然后将re.finditer()
内re.search()
。
pattern = '[A-Za-z]'
string = "abc"
if re.search(pattern, string) is not None:
for thing in re.finditer(pattern, string):
print('Found this thing: ' + thing[0])
返回值:
Found this thing: a
Found this thing: b
Found this thing: c
因此,如果您想同时使用这两个选项,请将该else:
子句与if re.search()
条件语句一起使用。
pattern = "1"
string = "abc"
if re.search(pattern, string) is not None:
for thing in re.finditer(pattern, string):
print('Found this thing: ' + thing[0])
else:
print('do this because nothing was found')
返回值:
do this because nothing was found
下面的上一个答复(不足,仅在上面阅读)
如果.finditer()与模式不匹配,则它将在相关循环内不执行任何命令。
所以:
- 在 用于迭代正则表达式 的循环之前, 设置变量
- 在用于迭代正则表达式返回的循环 之后(之外) 调用变量
这样,如果正则表达式调用未返回任何内容,则该循环将不会执行,并且循环后的变量调用将返回与设置时完全相同的变量。
下面,示例1演示了正则表达式查找模式。示例2显示了正则表达式找不到模式,因此循环中的变量从未设置。 示例3 显示了我的建议-
在regex循环之前设置变量,因此,如果regex找不到匹配项(随后不触发循环),则循环后的变量调用将返回初始变量集(确认找不到正则表达式模式)。
记住要导入 import re 模块。
示例1(在字符串“ hello world”中搜索字符“ he”将返回“ he”)
my_string = 'hello world'
pat = '(he)'
regex = re.finditer(pat,my_string)
for a in regex:
b = str(a.groups()[0])
print(b)
# returns 'he'
示例2(在字符串“ hello world”中搜索字符“ ab”不匹配任何内容,因此不会执行“ for a in
regex:”循环,并且不会为b变量分配任何值。)
my_string = 'hello world'
pat = '(ab)'
regex = re.finditer(pat,my_string)
for a in regex:
b = str(a.groups()[0])
print(b)
# no return
示例3(再次搜索字符“ ab”,但是这次在循环之前将变量b设置为“ CAKE”,然后在循环外部调用变量b返回初始变量-即“ CAKE”),因为循环未执行)。
my_string = 'hello world'
pat = '(ab)'
regex = re.finditer(pat,my_string)
b = 'CAKE' # sets the variable prior to the for loop
for a in regex:
b = str(a.groups()[0])
print(b) # calls the variable after (and outside) the loop
# returns 'CAKE'
还值得注意的是,在设计要输入到正则表达式的模式时,请确保使用括号指示组的开始和结束。
pattern = '(ab)' # use this
pattern = 'ab' # avoid using this
回到最初的问题:
由于找不到任何内容不会执行for循环(对于regex中的for),用户可以预加载变量,然后在for循环之后检查该变量是否为原始加载值。这将使用户知道是否未找到任何内容。
my_string = 'hello world'
pat = '(ab)'
regex = re.finditer(pat,my_string)
b = 'CAKE' # sets the variable prior to the for loop
for a in regex:
b = str(a.groups()[0])
if b == ‘CAKE’:
# action taken if nothing is returned