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

如何保留匹配指定正则模式的内容,替换其余所有字符?

Got it, let's figure out how to keep only those matching patterns and strip everything else out. Here's what you can do:

Core Approach

Instead of fumbling with replacing non-matching content (which can get messy), the cleanest solution is to directly extract all occurrences of your target pattern from the input string. Your pattern logic is already on point—we just need to use regex tools that capture all matches instead of doing replacements.

Your Target Regex Pattern

First, let's formalize the pattern you need (you likely already have this, but it's good to confirm):

102\d{3}-\d{3}:\d{5}-\d{3,4}

Quick breakdown:

  • 102: Exact required starting sequence
  • \d{3}: Exactly 3 digits
  • -: Literal hyphen
  • \d{3}: Another set of 3 digits
  • :: Literal colon
  • \d{5}: Exactly 5 digits
  • -: Literal hyphen
  • \d{3,4}: 3 or 4 digits (covers both your allowed endings)

Implementation Examples (Common Languages)

Python

Use re.findall() to grab all matches, then join them into your preferred output format (e.g., newlines, commas):

import re

input_text = "Random text 102123-456:78901-123 more words 102789-012:34567-890abc 102456-789:01234-5678"
pattern = r'102\d{3}-\d{3}:\d{5}-\d{3,4}'

# Fetch all matching patterns as a list
matches = re.findall(pattern, input_text)

# Join matches with newlines (swap with ',' for comma-separated output)
clean_output = '\n'.join(matches)

print(clean_output)

Sample output:

102123-456:78901-123
102789-012:34567-890
102456-789:01234-5678

JavaScript

Use String.match() with the global flag (g) to capture all matches:

const inputText = "Random text 102123-456:78901-123 more words 102789-012:34567-890abc 102456-789:01234-5678";
const pattern = /102\d{3}-\d{3}:\d{5}-\d{3,4}/g;

// Get matches (fallback to empty array if no matches are found)
const matches = inputText.match(pattern) || [];

// Join into clean, readable output
const cleanOutput = matches.join('\n');

console.log(cleanOutput);

If You Prefer a Replacement Approach

If you really want to use regex replacement to strip non-matching content, you can use a negative lookahead to target any characters that aren't part of your pattern. This is less intuitive, but here's how it works in Python:

clean_output = re.sub(r'(?:(?!102\d{3}-\d{3}:\d{5}-\d{3,4}).)+', '', input_text)

This replaces any sequence of characters that doesn't initiate your target pattern with an empty string, leaving only the matching segments intact.

Edge Cases Covered

  • 1 to 5 occurrences of your pattern in the input
  • Any random characters (spaces, letters, special symbols) between patterns
  • Both 3-digit and 4-digit endings in the final number group

内容的提问来源于stack exchange,提问作者configure.ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:44:56