仅对长度大于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:
- 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 matchw0lfinside it). - It didn't restrict the length of the word, so it would match short words like
12which you want to keep.
This updated regex fixes both issues while ensuring we only target the words you want to replace.
内容的提问来源于stack exchange,提问作者Batch
相关产品推荐
相关产品推荐

