提问人:Dimuthu Madushan 提问时间:11/10/2023 更新时间:11/10/2023 访问量:42
芭蕾舞演员中的REGEX图案搜索
REGEX pattern search in 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);
}
我可以得到一些帮助来使用芭蕾舞演员来写这篇文章吗?
答:
2赞
Dimuthu Madushan
11/10/2023
#1
您可以使用随发布时宣布的功能。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 文档。
评论