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

仅对长度大于2且含数字的单词应用RegEx替换

Solution to Replace Long Numeric-Containing Words with Asterisks

Got it, let's tweak your regex to meet the exact requirement: replacing entire words that contain at least one digit AND are longer than 2 characters with asterisks matching the original word length.

The Improved Regex

Here's the regex you need:

\b(?=\w*\d)\w{3,}\b

Breakdown of the Regex

Let's break down each part so you understand how it works:

  • \b: Word boundary marker, ensures we're matching entire words (not partial chunks of text).
  • (?=\w*\d): Positive lookahead that checks if the word contains at least one digit (\d) somewhere within it (preceded by any number of word characters \w*).
  • \w{3,}: Matches 3 or more word characters (letters, digits, underscores—perfect for your alphanumeric word use case).
  • \b: Closing word boundary to complete the full word match.

How to Use It (with Examples)

Since replacing with asterisks of the same length requires a bit more than just a static replacement string, here are examples in common languages:

JavaScript

const originalStr = "The boy cried w0lf aga1n for 2 days in row! 12 12345";
const modifiedStr = originalStr.replace(/\b(?=\w*\d)\w{3,}\b/g, match => '*'.repeat(match.length));
console.log(modifiedStr);
// Output: "The boy cried **** ***** for 2 days in row! 12 *****"

Python

import re

original_str = "The boy cried w0lf aga1n for 2 days in row! 12 12345"
modified_str = re.sub(r'\b(?=\w*\d)\w{3,}\b', lambda match: '*' * len(match.group()), original_str)
print(modified_str)
# Output: "The boy cried **** ***** for 2 days in row! 12 *****"

Why Your Original Regex Didn't Work

Your initial regex [a-z]*\d+[a-z]* had two key limitations:

  1. It didn't enforce word boundaries, so it could match partial parts of words (e.g., if you had a word like testw0lf, it would still match w0lf inside it).
  2. It didn't restrict the length of the word, so it would match short words like 12 which you want to keep.

This updated regex fixes both issues while ensuring we only target the words you want to replace.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:54:52