[英]Regex: starts with messages and string between parent message curly brace
我想获取所有的消息数据。 这样它应该在父消息的大括号之间查找消息和所有数据。 使用下面的模式,我没有得到所有的父体。
String data = "syntax = \"proto3\";\r\n" +
"package grpc;\r\n" +
"\r\n" +
"import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
"import \"google/api/annotations.proto\";\r\n" +
"import \"google/protobuf/wrappers.proto\";\r\n" +
"import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
"\r\n" +
"message Acc {\r\n" +
" message AccErr {\r\n" +
" enum Enum {\r\n" +
" UNKNOWN = 0;\r\n" +
" CASH = 1;\r\n" +
" }\r\n" +
" }\r\n" +
" string account_id = 1;\r\n" +
" string name = 3;\r\n" +
" string account_type = 4;\r\n" +
"}\r\n" +
"\r\n" +
"message Name {\r\n" +
" string firstname = 1;\r\n" +
" string lastname = 2;\r\n" +
"}";
List<String> allMessages = new ArrayList<>();
Pattern pattern = Pattern.compile("message[^\\}]*\\}");
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
String str = matcher.group();
allMessages.add(str);
System.out.println(str);
}
}
我期待在我的大小为 2 的字符串数组列表中得到如下响应。
allMessage.get(0)
应该是:
message Acc {
message AccErr {
enum Enum {
UNKNOWN = 0;
CASH = 1;
}
}
string account_id = 1;
string name = 3;
string account_type = 4;
}
allMessage.get(1)
应该是:
message Name {
string firstname = 1;
string lastname = 2;
}
试试这个你的正则表达式。 它将message
锚定在行的开头,并使用正向前瞻来查找下一条消息或消息的结尾。
Pattern.compile("(?s)\r\n(message.*?)(?=\r\nmessage|;$)")
// or
Pattern.compile("(?s)\r?\n(message.*?)(?=\r?\nmessage|;$)")
也没有拆分、解析或管理嵌套大括号:)
首先删除出现在行首的"message"
之前的输入,然后在换行符上拆分,然后是"message"
(在拆分中包含换行符,以便使用干预父消息的换行符):
String[] messages = data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)");
见现场演示。
如果您确实需要List<String>
,请将结果传递给Arrays.asList()
:
List<String> = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.