Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何';如果finditer(…)没有匹配项';?_Python_Regex - Fatal编程技术网

在python中,如何';如果finditer(…)没有匹配项';?

在python中,如何';如果finditer(…)没有匹配项';?,python,regex,Python,Regex,当FindItemer()找不到任何内容时,我想做一些事情 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() 不回答的

当FindItemer()找不到任何内容时,我想做一些事情

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()
不回答的相关帖子:

  • 计算finditer匹配项:(我不需要计算,我只需要知道是否没有匹配项)
  • finditer vs match:(表示始终必须在finditer返回的迭代器上循环)
[编辑]
-我对列举或计算总产出不感兴趣。仅当找到其他未找到的操作时。

-我知道我可以将finditer放入一个列表中,但这对于大型字符串来说效率很低。一个目标是内存利用率低。

如果性能不是问题,只需使用
findall
list(finditer(…)
,返回列表即可

否则,您可以使用
next
“窥视”生成器,然后在它引发
StopIteration
时正常循环。虽然还有其他方法,但这对我来说是最简单的:

import itertools
import re

pattern = "1"
string = "abc"  
matched_iter = re.finditer(pattern, string)

try:
    first_match = next(matched_iter)
except StopIteration:
    print("No match!") # action for no match
else:
    for m in itertools.chain([first_match], matched_iter):
        print(m.group())

您可以使用
next
探测迭代器,然后
chain
将结果返回到一起,但
StopIteration
除外,这意味着迭代器为空:

import itertools as it

matches = iter([])
try:
    probe = next(matches)
except StopIteration:
    print('empty')
else:
    for m in it.chain([probe], matches):
        print(m)
对于您的解决方案,您可以直接检查
m
,事先将其设置为
None

matches = iter([])
m = None
for m in matches:
    print(m)
if m is None:
    print('empty')

如果字符串中没有匹配项,它将打印原始字符串。 它将替换字符串的位置
n

更多参考:

更新日期:2020年10月4日 使用
re.search(模式、字符串)
检查模式是否存在

pattern = "1"
string = "abc"

if re.search(pattern, string) is None:
    print('do this because nothing was found')
返回:

do this because nothing was found
Found this thing: a
Found this thing: b
Found this thing: c
do this because nothing was found
如果要迭代返回,请将
re.finditer()
放在
re.search()

返回:

do this because nothing was found
Found this thing: a
Found this thing: b
Found this thing: c
do this because nothing was found
因此,如果您想要两个选项,请将
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
Found this thing: a
Found this thing: b
Found this thing: c
do this because nothing was found
下面是以前的答复(不够,请阅读上面的内容) 如果.finditer()与模式不匹配,则它不会在相关循环中执行任何命令

因此:

  • 在循环之前设置变量,用于迭代正则表达式返回
  • 在用于迭代正则表达式返回的循环之后调用变量
这样,如果regex调用没有返回任何内容,循环将不会执行,并且循环后的变量调用将返回与它设置的变量完全相同的变量

下面的示例1演示了查找模式的正则表达式。示例2显示正则表达式没有找到模式,因此循环中的变量从未设置。 示例3显示了我的建议-变量设置在正则表达式循环之前,因此如果正则表达式未找到匹配项(随后未触发循环),则循环之后的变量调用将返回初始变量集(确认未找到正则表达式模式)

请记住导入导入重新导入模块

示例1(搜索字符串“hello world”中的字符“he”将返回“he”)

示例2(搜索字符串“hello world”中的字符“ab”与任何内容都不匹配,因此不会执行“for a in regex:”循环,也不会为b变量分配任何值。)

示例3(再次搜索字符'ab',但这次将变量b设置为循环前的'CAKE',并在循环外调用变量b,返回初始变量,即'CAKE',因为循环未执行)

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

pattern = '(ab)' # use this
pattern = 'ab' # avoid using this
回到最初的问题:

因为找不到任何东西都不会执行for循环(对于regex中的),所以用户可以预加载变量,然后在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

如果它是一个迭代器,您必须对它进行迭代以知道它是空的。除非正则表达式库增加了一个繁荣,否则您最终将不得不做类似的事情,这是合理的,足以满足您的需求。将iterable值转换为列表,您可以轻松地将其用于任何进一步的操作。另一种方法:如果
如果重新搜索(模式,s):
则存在匹配。请参阅将其转换为列表:
list(re.finditer(pattern,string))
如果没有大量匹配项,您不会注意到性能上的差异。只将
下一个
调用放入
try
,并将剩余的快乐路径放入
else
。我喜欢m=None hack。这很简单,在面试时我能记得。乍一看,try/catch看起来有点复杂,我认为这有点忽略了重点。问题是如何处理“如果什么都没有找到”的案子。@Leo Ufimtsev,这很公平。当.finditer()找不到任何内容时,它会绕过for循环中的后续条件代码(因为没有“for a in…”)。当用户预加载变量时,它在“for循环”期间不会被替换。因此,在循环之后,用户可以检查变量的预加载值,以测试是否没有发生任何情况。我需要补充我的答案@LeoUfimtsev使用re.search()查看我的更新,选择“is None”或“is not None”来构建更好的建议。让我知道这是否有帮助!我佩服你的坚持。我认为这应该得到奖励。这确实是一个很好的解决办法。标记为被接受的答案。谢谢你的输入。