在python中,如何“如果finditer(...)没有匹配项”?

在python中,如何“如果finditer(...)没有匹配项”?,第1张

在python中,如何“如果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: aFound this thing: bFound 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 loopfor a in regex:    b = str(a.groups()[0])print(b) # calls the variable after (and outside) the loop# returns 'CAKE'

还值得注意的是,在设计要输入到正则表达式的模式时,请确保使用括号指示组的开始和结束。

pattern = '(ab)' # use thispattern = '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 loopfor a in regex:    b = str(a.groups()[0])if b == ‘CAKE’:    # action taken if nothing is returned


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5650384.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存