Ballerina 中的 REGEX 模式搜索

问题描述 投票:0回答:1

我需要编写一段代码来按正则表达式模式分割字符串。在java中,我可以使用这种方法。

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}) \\[(.*)\\] ([^ ]*) ([^ ]*) - (.*)$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(samples[0]);

if (m.matches() && m.groupCount() == 6) {
    String date = m.group(1);
    String time = m.group(2);
    String threadId = m.group(3);
    String priority = m.group(4);
    String category = m.group(5);
    String message = m.group(6);
}

我可以得到一些帮助来使用芭蕾舞演员写这个吗?

regex regex-group ballerina
1个回答
0
投票

您可以使用随

lang.regexp
版本发布的
2201.6.0
功能。

import ballerina/io;
import ballerina/lang.regexp;

public function main() {
    string inputStr = "1999-11-27 15:49:37,459 [thread-x] ERROR mypackage - Catastrophic system failure";
    string:RegExp re = re `^(\d{4}-\d{2}-\d{2})\s(\d{2}:\d{2}:\d{2},\d{3})\s\[(.+)\]\s(.+)\s(.+)\s-\s(.+)$`;
    regexp:Groups? result = re.findGroups(inputStr);
    if result is () || result.length() != 7 {
        return;
    }
    regexp:Span date = <regexp:Span>result[1]; // casting since we know the result is not ()
    regexp:Span time = <regexp:Span>result[2];
    regexp:Span threadId = <regexp:Span>result[3];
    regexp:Span priority = <regexp:Span>result[4];
    regexp:Span category = <regexp:Span>result[5];
    regexp:Span message = <regexp:Span>result[6];

    io:println(date.substring()); // prints 1999-11-27
    io:println(time.substring()); // prints 15:49:37,459
    io:println(threadId.substring()); // prints thread-x
    io:println(priority.substring()); // prints ERROR
    io:println(category.substring()); // prints mypackage
    io:println(message.substring()); // prints Catastrophic system failure
}

请参阅API文档了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.