You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用正则表达式re.search检测单词列表中的单词是否存在于字符串

用正则表达式匹配完整单词并获取首个匹配结果

问题场景

现有单词列表:

words = ['abandon', 'abandonments', 'abandons', 'abandonment', 'abandon', 'abandoned', 'abandons', 'abandoning']

需要判断列表中任意完整单词是否存在于以下句子中:

sentence = "The children abandoned themselves to the delights of the warm summer day."

要求仅使用re.search获取第一个匹配结果,同时得到匹配字符串及其位置跨度,且必须匹配完整单词(即结果应为abandoned而非abandon)。

解决方案

要实现完整单词匹配,核心是利用正则的**单词边界\b**避免匹配子串,同时先对单词列表去重减少冗余匹配项。具体代码如下:

import re

words = ['abandon', 'abandonments', 'abandons', 'abandonment', 'abandon', 'abandoned', 'abandons', 'abandoning']
sentence = "The children abandoned themselves to the delights of the warm summer day."

# 去重并生成正则匹配模式:用|分隔单词,前后加单词边界确保完整匹配
unique_words = list(set(words))
pattern = r'\b(' + '|'.join(unique_words) + r')\b'

# 执行搜索获取第一个匹配项
match_result = re.search(pattern, sentence)
print(match_result)

输出结果

<re.Match object; span=(13, 21), match='abandoned'>

说明

  • 单词边界\b会确保匹配独立单词,不会把abandoned中的abandon误判为匹配项;
  • 对单词列表去重是为了简化正则模式,避免重复的备选匹配项;
  • re.search会返回第一个符合条件的匹配结果,包含位置跨度和匹配字符串。

内容的提问来源于stack exchange,提问作者ZZZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 02:55:31