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

编写正则表达式匹配potato的漏写/颠倒字母场景,修正反转词误匹配

Solving the "potato" Regex Match Issue

Let's break down the problem first: your original regex is way too permissive—it only checks that characters are from "potato" and fall within a length range, but ignores logical character order and counts. That's why it’s matching fully reversed strings like otatop. Here’s a targeted fix that covers your exact use cases while eliminating false positives.

The Fixed Regex

(?!otatop)(?:
  # Case 2: Missing one character (length 5, includes your "ptato" example)
  otato|ptato|poato|potto|potao|potat|
  # Case 1: Adjacent character swap (length 6, includes your "potaot" example)
  optato|ptoato|poatto|pottao|potaot
)

How It Works

  1. Block False Positives: The (?!otatop) negative lookahead explicitly excludes the fully reversed string you mentioned. You can add other unwanted matches here if you run into similar issues later.
  2. Single Character Deletion Coverage: The first group lists every possible 5-character string formed by removing exactly one character from "potato"—this covers all typo scenarios where a user skips a letter, including your ptato example.
  3. Adjacent Swap Coverage: The second group lists every possible 6-character string from swapping one pair of adjacent characters in "potato"—this covers fast-typos where users mix up nearby keys, like your potaot example.

Simplified Version (For Exact Two Errors Only)

If you don’t need to cover all possible single-character typos, just target the two specific inputs you noted:

(?!otatop)(?:ptato|potaot)

Why Your Original Regex Failed

(?=[potato]{5,6})p?o?t?a?t?o? has two critical flaws:

  • It doesn’t enforce logical character counts (e.g., it allows multiple ps or missing as, as long as total length is 5-6).
  • It has zero order restrictions—any permutation of "potato" characters within the length range will match, including fully reversed strings like otatop.

Test Cases

  • Matches: ptato, potaot, otato, poato, potto, potao, potat, optato, ptoato, poatto, pottao
  • Does Not Match: otatop, potatox, pottato, tomato

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:57:25