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

如何使用Ballerina实现正则表达式拆分字符串(附Java示例)

对应的Ballerina正则拆分字符串实现

下面是与你提供的Java代码等价的Ballerina实现,同样通过正则表达式拆分日志字符串:

import ballerina/regex;
import ballerina/io;

public function main() {
    string[] samples = ["1999-11-27 15:49:37,459 [thread-x] ERROR mypackage - Catastrophic system failure"];
    string regex = "(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2},\\d{3}) \\[(.*)\\] ([^ ]*) ([^ ]*) - (.*)$";
    
    regex:Pattern pattern = regex:compile(regex);
    regex:Matcher matcher = pattern.matcher(samples[0]);

    if (matcher.matches() && matcher.groupCount() == 6) {
        string date = matcher.group(1);
        string time = matcher.group(2);
        string threadId = matcher.group(3);
        string priority = matcher.group(4);
        string category = matcher.group(5);
        string message = matcher.group(6);
        
        // 可根据需求添加后续处理逻辑,比如打印结果
        io:println(date, " | ", time, " | ", threadId, " | ", priority, " | ", category, " | ", message);
    }
}

关键说明:

  • Ballerina需要导入ballerina/regex模块来使用正则相关API,这套API设计和Java的java.util.regex体系逻辑一致,上手成本低
  • 正则字符串中的反斜杠\需要转义为\\,和Java字符串的转义规则保持相同
  • 通过regex:Pattern编译正则表达式,regex:Matcher执行匹配操作,最终用group()方法提取对应分组的内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:40:11