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

Java字符串处理:无需正则表达式生成A{i}+B{i}+C{i}格式公式

无需正则表达式的实现方法

完全不用正则,用字符串格式化或直接拼接就能轻松实现,下面是几种主流语言的示例:

Python

  • 使用f-string(Python 3.6+),语法简洁直观:
i = 0
formula = f"A{i}+B{i}+C{i}"
print(formula)  # 输出: A0+B0+C0
  • 兼容旧版本的str.format():
i = 1
formula = "A{}+B{}+C{}".format(i, i, i)
print(formula)  # 输出: A1+B1+C1

JavaScript

  • 模板字符串(ES6+):
let i = 2;
const formula = `A${i}+B${i}+C${i}`;
console.log(formula); // 输出: A2+B2+C2
  • 基础字符串拼接:
let i = 3;
const formula = "A" + i + "+B" + i + "+C" + i;
console.log(formula); // 输出: A3+B3+C3

Java

  • String.format()方法:
int i = 4;
String formula = String.format("A%d+B%d+C%d", i, i, i);
System.out.println(formula); // 输出: A4+B4+C4
  • 直接字符串拼接:
int i = 5;
String formula = "A" + i + "+B" + i + "+C" + i;
System.out.println(formula); // 输出: A5+B5+C5

核心逻辑就是把变量i直接插入到字符串的对应位置,比正则表达式简单得多,也更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:13:14