在Notepad++中如何仅将方括号内的文本转换为大写并保留方括号
解决方案
你目前使用的正则\[([a-z][\S\s]+?)\]可以正常匹配目标内容,不同场景下的替换规则如下:
文本编辑器/通用正则工具替换规则
- VS Code、Sublime Text:替换内容填
[\U$1] - Notepad++:替换内容填
[\U\1] - GNU sed(Linux环境):完整命令为
sed 's/\[\([a-z][\S\s]*?\)\]/[\U\1]/g' 目标文件路径
编程语言实现示例
如果是在代码中做替换,常见语言的实现方式如下:
JavaScript
const inputStr = '测试文本[sample1]其他内容[sample2]'; const outputStr = inputStr.replace(/\[([a-z][\S\s]+?)\]/g, (_, capture) => `[${capture.toUpperCase()}]`);
Python
import re input_str = '测试文本[sample1]其他内容[sample2]' output_str = re.sub(r'\[([a-z][\S\s]+?)\]', lambda m: f"[{m.group(1).upper()}]", input_str)
Java
import java.util.regex.*; public class UpperCaseBracketContent { public static void main(String[] args) { String inputStr = "测试文本[sample1]其他内容[sample2]"; Pattern pattern = Pattern.compile("\\[([a-z][\\S\\s]+?)\\]"); Matcher matcher = pattern.matcher(inputStr); StringBuffer sb = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(sb, "[" + matcher.group(1).toUpperCase() + "]"); } matcher.appendTail(sb); String outputStr = sb.toString(); } }
优化提示
如果你不需要匹配方括号内带换行的内容,可以把正则简化为\[([a-z].*?)\],可读性更高,匹配效率也略有提升。
内容的提问来源于stack exchange,提问作者Kyshakk
相关产品推荐
相关产品推荐

