Salesforce Apex子串提取未达预期,Comments字段无法正常赋值
问题排查方向
- 核心原因是Apex字符串方法的特性+换行符不匹配:
substringBefore()方法在找不到传入的分隔符时,会直接返回空字符串,而非返回剩余全部内容。Email-to-Case生成的Case描述、外部系统传入的文本,换行符通常是Windows格式的\r\n,甚至如果Internal Comments对应的内容是Description的最后一段,行尾根本没有换行符,此时你写的.substringBefore('\n')匹配不到分隔符,自然返回空,导致Comments赋值失败。 - 校验字段写入权限:确认触发器运行用户对Comments字段有编辑权限,排除字段级安全限制、只读属性拦截写入的情况,这类问题不会报语法错误,只会静默赋值失败。
- 检查标签匹配精度:如果传入的Description里
Internal Comments:标签存在大小写偏差、中间多空格(比如写成Internal Comments:、internal comments:),会导致substringAfter('Internal Comments: ')匹配不到正确起始位置,返回空值。
修复代码
先统一处理换行符差异,同时兼容“Internal Comments是最后一行、无后续换行”的边界场景,代码如下:
// 统一换行符格式,消除CR、CRLF、LF差异 String normalizedContent = c.Description ?.replace('\r\n', '\n') ?.replace('\r', '\n'); if(String.isNotBlank(normalizedContent)){ // 提取Subject,trim掉首尾多余空白、换行 String subjectRaw = normalizedContent.substringAfter('Subject: '); c.Subject = subjectRaw?.substringBefore('\nInternal Comments: ')?.trim(); // 提取Comments,兼容无后续换行的场景 String commentRaw = normalizedContent.substringAfter('Internal Comments: '); if(commentRaw != null){ Integer lineBreakIndex = commentRaw.indexOf('\n'); c.Comments = lineBreakIndex == -1 ? commentRaw.trim() : commentRaw.left(lineBreakIndex).trim(); } }
调试时可以在赋值前加
System.debug(commentRaw.escapeJava());打日志,日志会把不可见的控制符转成可见字符(比如\r会直接显示出来),可以快速确认是不是特殊字符导致的匹配问题。
内容的提问来源于stack exchange,提问作者Gtunux
相关产品推荐
相关产品推荐

