帮助 re.search python 长度

1 投票
3 回答
5469 浏览
提问于 2025-04-16 19:04

可以读取re.search的输出长度吗?

比如说:

import re

list=['lost','post','cross','help','cost']

for i in range(len(list)):
  output = re.search('os', list[i])

我可以读取输出的长度吗?

3 个回答

0

re.search() 会返回一个匹配对象,这个对象里面有一个叫做 span 的方法。这个方法会给你两个东西,一个是匹配的开始位置,另一个是匹配的结束位置。

2

首先,把内置的 list 重新命名是个很糟糕的主意。其次,这样遍历列表的方式也不是很符合 Python 的风格。Python 的循环都是“为每个”循环,所以你只需要这样做:

word_list = ['lost','post','cross','help','cost']
for word in word_list:
    match = re.search("os", word)

话虽如此,你可能是在寻找匹配的 startend 方法,这两个方法可以告诉你在被搜索的文本中,某个匹配项的开始和结束位置。

word_list = ['lost','post','cross','help','cost']
for word in word_list:
    match = re.search("os", word)
    if match is not None:
        print match.start(), match.end()

显然,差异会体现在长度上。给定你的单词列表,这将打印出:

1 3
1 3
2 4
1 3
3

在这种情况下,输出的长度和输入的长度是一样的,因为你是在寻找一个特定的子字符串。当你在 'lost' 中搜索时,匹配的长度会是 2,因为这就是你搜索的内容的长度。如果你想区分“找到”和“没找到”,记住 re.search 如果没有匹配会返回 None。如果你真的需要长度,可以这样做:

for i in range(len(list)):
    length = 2 if re.search('os', list[i]) else 0

不过我建议使用更常见的 foreach 循环:

for item in list:
    length = 2 if re.search('os', item) else 0

如果你只是想检查一个字符串是否出现在另一个字符串里面,你可以用 in 操作符来做到这一点:

for item in list:
    length = 2 if 'os' in item else 0

现在,如果你在寻找更复杂的正则表达式,你可以从匹配中提取组 0,这就是整个子字符串,然后检查它的长度:

for item in list:
    match = re.search('[aeiou]s', item)
    length = len(match.group(0)) if match else 0

撰写回答