当前位置: 首页 > news >正文

Groovy (JSR223) 字符串语法

Groovy (JSR223) 的字符串语法 ⭐⭐⭐⭐⭐

1. 单引号字符串(不支持插值)

def str = 'Hello World'
def name = 'Tom'
def str2 = 'Hello ${name}'  // 输出: Hello ${name} (不会插值)

2. 双引号字符串(支持插值)

def name = 'Tom'
def str = "Hello ${name}"  // 输出: Hello Tom
def str2 = "Line1\nLine2"  // 支持转义

3. 三单引号(多行字符串,不转义,不插值)⭐⭐⭐

def json = '''
{"name": "张三","path": "C:\\Users\\test\\file.txt","regex": "\\d+\\.\\d+","quote": "He said 'hello'"
}
'''
// 所有字符都按原样输出,无需转义

4. 三双引号(多行字符串,不转义,支持插值)⭐⭐⭐⭐⭐

def name = "张三"
def userId = "10001"def json = """
{"name": "${name}","userId": "${userId}","path": "C:\\Users\\test\\file.txt","regex": "\\d+\\.\\d+","message": "He said 'hello' and \"goodbye\""
}
"""
// 支持变量插值,且无需转义反斜杠和引号

5. 斜杠字符串(正则表达式专用)

def pattern = /\d+\.\d+/  // 无需转义反斜杠
def path = /C:\Users\test\file.txt/  // 路径也很方便

二、BeanShell 的字符串语法(受限)

1. 只支持双引号字符串

String str = "Hello World";
String name = "Tom";
String str2 = "Hello " + name;  // 必须用 + 拼接

2. 必须转义特殊字符

// ❌ BeanShell 不支持三引号
String json = """
{"name": "test"
}
""";  // 语法错误!// ✅ 必须这样写(痛苦)
String json = "{\n" +"  \"name\": \"test\",\n" +"  \"path\": \"C:\\\\Users\\\\test\\\\file.txt\"\n" +"}";

3. BeanShell 的多行字符串解决方案

方案A: 字符串拼接(传统方式)

String json = "{" +"\"code\": 0," +"\"message\": \"success\"," +"\"data\": {" +"\"userId\": \"10001\"," +"\"name\": \"张三\"," +"\"path\": \"C:\\\\Users\\\\test\\\\file.txt\"" +"}" +
"}";

方案B: StringBuilder(稍好一点)

StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append("  \"code\": 0,\n");
sb.append("  \"message\": \"success\",\n");
sb.append("  \"data\": {\n");
sb.append("    \"userId\": \"10001\",\n");
sb.append("    \"name\": \"张三\",\n");
sb.append("    \"path\": \"C:\\\\Users\\\\test\\\\file.txt\"\n");
sb.append("  \n");
sb.append("}");String json = sb.toString();

方案C: 使用 JSON 库(推荐)⭐⭐⭐

import org.json.JSONObject;JSONObject json = new JSONObject();
json.put("code", 0);
json.put("message", "success");JSONObject data = new JSONObject();
data.put("userId", "10001");
data.put("name", "张三");
data.put("path", "C:\Users\test\file.txt");  // 只需转义一次json.put("data", data);String jsonStr = json.toString(2);  // 2 表示缩进

三、实际对比示例

场景:返回包含特殊字符的 JSON

Groovy (JSR223) - 优雅 ⭐⭐⭐⭐⭐

def userId = vars.get("userId") ?: "10001"
def filePath = "C:\Users\test\data.txt"// 方式1: 三双引号(最推荐)
def json = """
{"code": 0,"message": "success","data": {"userId": "${userId}","name": "张三","path": "${filePath}","regex": "\\d+\\.\\d+","quote": "He said 'hello' and \"goodbye\"","sql": "SELECT * FROM users WHERE name = 'Tom'"}
}
"""SampleResult.setResponseData(json, "UTF-8")
SampleResult.setSuccessful(true)// 方式2: 三单引号(无插值)
def json = '''
{"code": 0,"message": "success","data": {"path": "C:\Users\test\data.txt","regex": "\\d+\\.\\d+","quote": "He said 'hello'"}
}
'''

BeanShell - 痛苦 ⭐

String userId = vars.get("userId");
if (userId == null) userId = "10001";// 方式1: 字符串拼接(痛苦)
String json = "{" +"\"code\": 0," +"\"message\": \"success\"," +"\"data\": {" +"\"userId\": \"" + userId + "\"," +"\"name\": \"张三\"," +"\"path\": \"C:\\\\Users\\\\test\\\\data.txt\"," +"\"regex\": \"\\\\d+\\\\.\\\\d+\"," +"\"quote\": \"He said 'hello' and \\\"goodbye\\\"\"" +"}" +
"}";ResponseData = json;
IsSuccess = true;// 方式2: 使用 JSON 库(推荐)
import org.json.JSONObject;JSONObject response = new JSONObject();
response.put("code", 0);
response.put("message", "success");JSONObject data = new JSONObject();
data.put("userId", userId);
data.put("name", "张三");
data.put("path", "C:\Users\test\data.txt");
data.put("regex", "\\d+\\.\\d+");
data.put("quote", "He said 'hello' and \"goodbye\"");response.put("data", data);ResponseData = response.toString(2);
IsSuccess = true;

四、转义字符对比表

字符 Groovy 单/双引号 Groovy 三引号 BeanShell
换行 \n \n 直接换行 \n
反斜杠 \ \ \ \
双引号 " " " \"
单引号 ' ' ' '
制表符 \t \t 直接 Tab \t
路径 C:\test C:\test C:\test C:\\test
正则 \d+ \d+ \d+ \\d+

五、完整实战对比

需求:返回包含 SQL、正则、路径的复杂 JSON

Groovy 实现(简洁)

def userId = vars.get("userId") ?: "10001"
def userName = vars.get("userName") ?: "张三"def response = """
{"code": 0,"message": "查询成功","data": {"userId": "${userId}","userName": "${userName}","sql": "SELECT * FROM users WHERE name = 'Tom' AND age > 18","regex": "^\\d{3}-\\d{4}-\\d{4}$","filePath": "C:\Users\test\documents\report.xlsx","jsonPath": "$..books[?(@.price < 10)]","xpath": "//div[@class='content']//p[1]","description": "He said: \"Hello, I'm Tom\" and she replied 'Hi!'"},"timestamp": ${System.currentTimeMillis()}
}
"""SampleResult.setResponseData(response, "UTF-8")
SampleResult.setResponseCode("200")
SampleResult.setSuccessful(true)

BeanShell 实现(复杂)

import org.json.JSONObject;String userId = vars.get("userId");
if (userId == null) userId = "10001";
String userName = vars.get("userName");
if (userName == null) userName = "张三";JSONObject response = new JSONObject();
response.put("code", 0);
response.put("message", "查询成功");JSONObject data = new JSONObject();
data.put("userId", userId);
data.put("userName", userName);
data.put("sql", "SELECT * FROM users WHERE name = 'Tom' AND age > 18");
data.put("regex", "^\\d{3}-\\d{4}-\\d{4}$");
data.put("filePath", "C:\Users\test\documents\report.xlsx");
data.put("jsonPath", "$..books[?(@.price < 10)]");
data.put("xpath", "//div[@class='content']//p[1]");
data.put("description", "He said: \"Hello, I'm Tom\" and she replied 'Hi!'");response.put("data", data);
response.put("timestamp", System.currentTimeMillis());ResponseData = response.toString(2);
ResponseCode = "200";
IsSuccess = true;

六、对比

特性 Groovy (JSR223) BeanShell
三引号支持 ✅ 支持 ''' 和 """ ❌ 不支持
字符串插值 ✅ "Hello ${name}" ❌ 必须用 + 拼接
多行字符串 ✅ 原生支持 ❌ 需要 + 或 StringBuilder
转义复杂度 ⭐ 简单 ⭐⭐⭐⭐⭐ 复杂
代码可读性 ⭐⭐⭐⭐⭐ 优秀 ⭐⭐ 较差
推荐度 ⭐⭐⭐⭐⭐ ⭐ 不推荐

建议

  • 新项目: 强烈推荐使用 JSR223 + Groovy 的三引号语法
  • 旧项目: 如果必须用 BeanShell,使用 JSON 库而不是字符串拼接
  • 迁移: 将 BeanShell 脚本迁移到 JSR223,可以大幅简化代码
http://www.jsqmd.com/news/421380/

相关文章:

  • PostgreSQL 启动、停止数据库
  • 基于k-means算法的校园美食推荐数据分析系统的设计与实现
  • 2026四大系列减速机供应商哪家值得选?速看,涡轮蜗杆减速机/硬齿面斜齿轮减速机 ,四大系列减速机销售厂家哪家好 - 品牌推荐师
  • 2026年行业内比较好的专利律所推荐 - 品牌排行榜
  • 基于Hadoop大数据的出行方式推荐系统
  • 耳鼻喉科手术显微镜厂家怎么选?新天医疗带来的几种思路 - 企师傅推荐官
  • 基于python的Bilibili青少年模式使用情况的数据分析系统设计与实现
  • 2026英国留学脱产申请机构深度评测:三大特色机构如何精准匹配你的需求 - 品牌2025
  • 避坑指南:物联网设备必须了解的SRRC、CCC与CTA认证
  • 2026年2月工业探伤铅房加工厂,专业制造与长期供货保障 - 品牌鉴赏师
  • 基于ECharts的海洋气象数据可视化平台设计与实现
  • 车铣复合、数控车床、走心机购买攻略:值得信赖的线上采购平台盘点 - 品牌推荐大师1
  • python基于flask框架的新能源汽车之家系统设计与实现-vue pycharm django
  • 2026靠谱的凤凰办理公司注册业务公司推荐哪家强 - 品牌排行榜
  • 2026年国内知名的张家港代账公司推荐哪家好 - 品牌排行榜
  • AI软件测试核心定义与核心难点(2)
  • 库存扣减
  • python基于flask水果商城销售系统-vue pycharm django
  • 2026年2月成都给水管/拉齐管/钢丝骨架管/钢带波纹管/双壁波纹管厂家综合指南 - 2026年企业推荐榜
  • 2026美国藤校申请中介精选,本科高端定制与留学机构推荐 - 品牌2025
  • 导弹防御塔题解
  • 2026年GEO推广企业实力排行榜:地域定向推广/海外精准营销/高ROI推广服务商综合实力排名 - 品牌推荐大师1
  • 从0到1上手RKNN-Toolkit2:AI模型部署全攻略
  • 2026年2月SPET-CT铅门供应商,专业防护与长期稳定供货 - 品牌鉴赏师
  • 2026年免熏蒸木托盘厂家推荐:聚焦湖北林桂与无锡太行,构建适配可靠的供应链选择 - 品牌推荐官
  • 2026年2月东莞防水补漏公司推荐榜,彰显本地服务实力 - 品牌鉴赏师
  • 造物主是不是在“养猪”?我们拼命进化,最后会被“格式化”吗?
  • 2026年电线电缆厂家实力推荐:高温/低烟无卤/铁氟龙/硅胶/PVC/医疗/无人机/机器人线缆及线束加工定制,专业源头工厂精选 - 品牌企业推荐师(官方)
  • 2026年真空抽气机组厂家推荐:靠谱品牌与选型要点 - 品牌推荐大师1
  • 指尖寻趣,解锁惊喜——盲盒扭蛋机小程序前端功能详解