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

在R语言中将任意长度的数字字符串替换为指定字符

解决方案

核心思路是用正则表达式匹配所有连续的数字序列,将其统一替换为nnnn,无论数字段长度是多少。

正则匹配规则

使用\d+作为匹配模式,该模式会匹配一个或多个连续的数字字符,刚好覆盖任意长度的数字部分需求。

常用语言实现示例

Python

import re

def replace_digits_with_nnnn(s):
    return re.sub(r'\d+', 'nnnn', s)

# 测试示例
test_cases = [
    "#100001032218888example1",
    "#1example2"
]
for case in test_cases:
    print(f"输入: {case}")
    print(f"输出: {replace_digits_with_nnnn(case)}")

执行输出:

输入: #100001032218888example1
输出: #nnnnexamplennnn
输入: #1example2
输出: #nnnnexamplennnn

JavaScript

function replaceDigitsWithNnnn(str) {
    return str.replace(/\d+/g, 'nnnn');
}

// 测试示例
const testCases = [
    "#100001032218888example1",
    "#1example2"
];
testCases.forEach(caseStr => {
    console.log(`输入: ${caseStr}`);
    console.log(`输出: ${replaceDigitsWithNnnn(caseStr)}`);
});

执行输出:

输入: #100001032218888example1
输出: #nnnnexamplennnn
输入: #1example2
输出: #nnnnexamplennnn

Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DigitReplacer {
    public static String replaceDigitsWithNnnn(String s) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(s);
        return matcher.replaceAll("nnnn");
    }

    public static void main(String[] args) {
        String[] testCases = {
            "#100001032218888example1",
            "#1example2"
        };
        for (String caseStr : testCases) {
            System.out.println("输入: " + caseStr);
            System.out.println("输出: " + replaceDigitsWithNnnn(caseStr));
        }
    }
}

执行输出:

输入: #100001032218888example1
输出: #nnnnexamplennnn
输入: #1example2
输出: #nnnnexamplennnn

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:27:40