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

Android Kotlin正则替换时获取被替换的子串

嗨,这个需求其实很常见——既要完成正则替换,又要把被换掉的内容存下来复用对吧?核心思路就是先用正则的捕获组锁定你要保留的子串,再分步骤完成「捕获保存」和「替换」。不同编程语言的实现细节略有不同,我给你举几个主流场景的例子:

JavaScript 场景实现

假设你的原字符串是 "Hello world!",想要把 "world" 替换成别的内容,同时把 "world" 存到变量里:

方法1:先捕获再替换

先通过正则匹配拿到目标子串,再执行替换操作:

const originalStr = "Hello world!";
const targetRegex = /(world)/; // 用括号把要保留的子串设为捕获组

// 第一步:捕获并保存子串
const matchResult = originalStr.match(targetRegex);
if (matchResult) {
  const savedSubstring = matchResult[1]; // 捕获组的第一个结果就是我们要的"world"
  // 第二步:执行替换
  const replacedStr = originalStr.replace(targetRegex, "there");
  
  console.log("保存的子串:", savedSubstring); // 输出: world
  console.log("替换后的字符串:", replacedStr); // 输出: Hello there!
}

方法2:在替换回调中捕获保存

如果不想单独写匹配逻辑,可以直接在replace的回调函数里拿到捕获组内容并保存:

const originalStr = "Hello world!";
const targetRegex = /(world)/;
let savedSubstring;

const replacedStr = originalStr.replace(targetRegex, (fullMatch, capturedGroup) => {
  savedSubstring = capturedGroup; // 在这里把捕获到的子串存到变量
  return "there"; // 返回替换后的内容
});

console.log(savedSubstring); // 输出: world
console.log(replacedStr); // 输出: Hello there!

Python 场景实现

用Python的re模块同样可以轻松实现,核心还是捕获组的用法:

方法1:先匹配捕获再替换

import re

original_str = "Hello world!"
target_pattern = r"(world)"

# 捕获目标子串
match_obj = re.search(target_pattern, original_str)
if match_obj:
    saved_sub = match_obj.group(1)  # 获取捕获组的内容
    # 执行替换
    replaced_str = re.sub(target_pattern, "there", original_str)
    
    print(f"保存的子串:{saved_sub}")  # 输出: world
    print(f"替换后的字符串:{replaced_str}")  # 输出: Hello there!

方法2:通过替换回调保存

import re

original_str = "Hello world!"
target_pattern = r"(world)"
saved_sub = None

def replace_callback(match):
    global saved_sub
    saved_sub = match.group(1)  # 保存捕获到的子串
    return "there"

replaced_str = re.sub(target_pattern, replace_callback, original_str)
print(saved_sub)  # 输出: world
print(replaced_str)  # 输出: Hello there!

核心要点总结

  • 捕获组是关键:给你需要保留的子串加上括号(),正则引擎会自动把这部分内容单独提取出来,方便后续保存。
  • 如果有多个匹配项:可以用findall遍历所有匹配结果,或者在替换回调里逐个处理并保存(比如存到数组里)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:50:28