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

正则表达式解密字符串:从rububbuber还原为rubber

Fixing the Regex for Decrypting "rububbuber" to "rubber"

Hey there! Let's work through this regex problem to get your decryption working correctly. The main issue with your current code is how you're handling the vowels in your regex pattern—converting the list to a string creates invalid regex syntax, which is why it isn't matching what you need.

Step 1: Correct the Regex Pattern

Instead of turning your vowels list into a string, we need to use a regex character class to match any single vowel. We'll also add a capture group to preserve the vowel, since we only want to remove the preceding "ub" (not the vowel itself).

The right pattern is r'ub([aeiou])':

  • ub matches the exact extra sequence we want to strip out
  • ([aeiou]) is a capture group that grabs the vowel following "ub"—this lets us keep the vowel in our final result

Step 2: Complete the Decrypt Function

We can use re.sub() to replace every match of our pattern with just the captured vowel. Here's the full working code:

import re

text = "rububbuber"

def decrypt(text):
    # Compile regex to match "ub" followed by any vowel, capture the vowel
    pattern = re.compile(r'ub([aeiou])')
    # Replace each match with the captured vowel (removes the extra "ub")
    decrypted_text = pattern.sub(r'\1', text)
    return decrypted_text

# Test the function
print(decrypt(text))  # Output: rubber

How It Works

Let's walk through the decryption of "rububbuber":

  1. The regex first matches ubu (the "ub" added before the original vowel u). We replace this with just u, leaving us with rubber's first three characters: rub.
  2. Next, it matches ube (the "ub" added before the original vowel e). We replace this with just e, completing the decrypted string: rubber.

Why Your Original Code Failed

When you ran vowel_string = str(vowels), it created the string ['a', 'e', 'i', 'o', 'u']—so your regex pattern became rub['a', 'e', 'i', 'o', 'u']. This tries to match literal characters like [ and ' which don't exist in your input, so it never found any matches to replace. Using a character class [aeiou] is the proper regex way to target any single vowel.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:14:44