您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

使用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

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显示了正则表达式找不到模式,因此循环中的变量从未设置。 显示了我的建议- 在regex循环之前设置变量,因此,如果regex找不到匹配项(随后不触发循环),则循环后的变量调用将返回初始变量集(确认找不到正则表达式模式)。

记住要导入 模块。

示例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
python 2022/1/1 18:49:54 有469人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶