编写正则表达式匹配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
- 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. - 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
ptatoexample. - 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
potaotexample.
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 missingas, 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
相关产品推荐
相关产品推荐

