无法获取第二个匹配项的索引

2024-04-27 08:02:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试着得到第二个匹配单词技能的索引。我想匹配的关键字,是目前单独而不是在一个句子。你知道吗

keyword = "skills"

def get_match_index(keyword, text):
    for sentence in text.split('\n'):
        if keyword == sentence.lower().strip():
            print(re.search(keyword,text))

这将返回第一次搜索的索引。 这是课文。你知道吗

Assessed and changed skills required to take company to next level in the IT, HR, Accounting.
-
College Station

Skills

我想在这里匹配关键字的第二个实例-“技巧”,一个标题,而不是一个句子。你知道吗


Tags: totextinforgetindexdef技能
3条回答

用另一种方法解决问题时,可以使用大写Skill

def get_match_index(keyword, text):
    start_match = text.index(keyword)
    end_match = start_match + len(text)
    return start_match, end_match

,它将以这种形式返回与来自这个正则表达式的span()调用相同的结果:

def get_match_index(keyword, text):
    pattern = re.compile(f"(?<=\n){keyword}")
    return pattern.search(text.lower()).span()

可以使用^{}而不是search

keyword = "skills"

def get_match_index(keyword, text):
    for sentence in text.split('\n'):
        if keyword == sentence.lower().strip():
            print(re.findall(keyword,text))

医生说:

re.search(pattern, string, flags=0) re.searScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance.

以及

re.findall(pattern, string, flags=0) Return all non-overlapping matches of pattern in string, as a list of strings.

最终得到了预期的效果。感谢@mrzasa推荐finditer方法。谢谢@Arne,你的结果匹配大写。你知道吗

pattern = r'(?i)^skills$'
regex = re.compile(pattern, re.IGNORECASE)

match_tup = [match.span() for match in re.finditer(r'(?i)^skills$',text,re.MULTILINE)]
print(match_tup)

相关问题 更多 >