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

如何用Python正则匹配包含play或improve的所有句子?

Hey there! Let's sort out that regex problem you're facing with matching sentences containing "play" or "improve" (and their variants).

First, let's clear up the mistake in your original "or" logic: using [play|improv] creates a character class, which matches any single character inside the brackets (so it would match p, l, a, y, |, i, m, etc.)—not the full word alternatives you want. Instead, you need to use a capturing group (play|improve) to match either of the complete word prefixes.

Here's the corrected regex pattern, tailored to your original requirements:

import re

# Corrected pattern with proper "or" grouping
pattern = re.compile(r'(?<=[ .])[\w ]*?(play|improve)\w+.*?\.')

Let's break down what each part does, just to make sure it aligns with your needs:

  • (?<=[ .]): Positive lookbehind to ensure we start matching right after a space or period (your original "sentence start" requirement)
  • [\w ]*?: Non-greedy match of word characters and spaces—this grabs the minimal text needed to reach our target words
  • (play|improve): The key fix! This group matches either the full "play" or "improve" prefix
  • \w+: Matches any trailing characters to cover variants like played, playing, improved, improving, etc.
  • .*?\.: Non-greedy match until we hit the next period, capturing the rest of the sentence

If you want to extract the full matching sentence fragments (not just the word prefix), adjust the pattern to capture the entire segment:

pattern_full = re.compile(r'(?<=[ .])([\w ]*?(play|improve)\w+.*?\.)')

# Example usage
text = """You should play more games. To improve your skills, practice daily. Playing tennis helps. Improved performance is key."""
matching_sentences = [match.group(1).strip() for match in pattern_full.finditer(text)]

for sentence in matching_sentences:
    print(sentence)

This will output:

You should play more games.
To improve your skills, practice daily.
Playing tennis helps.
Improved performance is key.

A quick note: If your text has edge cases like abbreviations with periods (e.g., "Mr. Jones loves playing chess"), the .*?\. might stop early. For those scenarios, you could refine the pattern to ignore abbreviations, but that adds complexity—this version works great for standard sentence structures.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:47:37