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

是否存在正则表达式使re.findall结果等价于指定split循环加搜索的代码?

Regex to Match Your Filtered Word List

Absolutely! Let's break down what your original code does first, then craft the regex that replicates its behavior perfectly.

Original Code Logic

Your code works in two key steps:

  • First, it trims leading/trailing whitespace from the input, then splits the string into words using one or more whitespace characters as separators.
  • Second, it filters out any word that meets either of these criteria:
    • Has three or more consecutive identical characters (e.g., iii, whaaaat)
    • Contains underscores, digits, or non-word characters (e.g., th_is, and2, kn-ow)

The remaining valid words are those made up solely of letters, with no runs of three identical characters.

The Regex You Need

Here's the regex that will return the exact same result as your code when used with re.findall():

r'(?<!\S)(?!.*(.)\1{2,})[a-zA-Z]+(?!\S)'

Breakdown of the Regex

Let's unpack each part to understand how it matches your requirements:

  • (?<!\S): A negative lookbehind that ensures the word starts at either the beginning of the string or right after whitespace (mimicking the split behavior for word boundaries).
  • (?!.*(.)\1{2,}): A negative lookahead that checks the entire word to ensure there are no sequences of three or more identical consecutive characters.
  • [a-zA-Z]+: Matches one or more letters only—this automatically excludes underscores, digits, and non-word characters (since none of those fall into the a-z/A-Z range).
  • (?!\S): A negative lookahead that ensures the word ends at either the end of the string or right before whitespace (again, aligning with the split behavior).

Testing It Out

If you run this regex against your sample doc:

doc = ' th_is is stuff. and2 3things if y4ou kn-ow ___ whaaaat iii mean)'
result = re.findall(r'(?<!\S)(?!.*(.)\1{2,})[a-zA-Z]+(?!\S)', doc)

You'll get ['is', 'if']—exactly the same output as your original code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:33:29