Ballerina 中的正则表达式模式搜索

标签 regex regex-group ballerina

我需要编写一段代码来按正则表达式模式分割字符串。在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);
}

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

最佳答案

您可以使用 2201.6.0 版本中宣布的 lang.regexp 功能。

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 docs了解更多信息。

关于Ballerina 中的正则表达式模式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77458904/

相关文章:

javascript - jQuery 类名可以包含任意数字

javascript - 正则表达式从具有多个方括号的字符串中查找匹配项

javascript - 正则表达式分组步骤说明

ballerina - 如何为芭蕾舞 Actor 设置http代理?

javascript - regexp 将 '1x' 和 '1x²' 替换为 'x' 和 'x²' (javascript)

php - 在 PHP 中使用 preg_match 通过多个分隔符拆分字符串

python - Python 正则表达式中的动态命名组

ballerina - 芭蕾舞女 Actor 是否支持排序?

ballerina - 如何在 Ballerina 中创建列表列表?

regex - Noob regex poser(匹配可能包含并且必须有)