我有一个多行的字符串,如下所示:
Alert null has been generated for policy ENG_POLICY Object: backtk2a.tk.fw.gs.com
Component:
Description: Client: ABC
Server: ABCD
Error: ABCDE Connection timed out
Group: Group1
Schedule: test
Job: JobName
Status: failed
Level:
Resolution: Please resolve
我需要提取
的值ABCD from Server: ABCD,
JobName from JOB: JobName,
ABC from Description: Client:ABC
有人可以解释我如何使用正则表达式提取上述三个值。 我试过这个,但它没有工作,因为它返回其余的字符串。请注意,字符串中的排序不是常量。
Pattern actionPattern = Pattern.compile(".*Description: Client: (.*) Job: (.*) .*", Pattern.CASE_INSENSITIVE);
答案 0 :(得分:0)
使用capturing groups捕获您想要的字符。
String s = "Alert null has been generated for policy ENG_POLICY Object: backtk2a.tk.fw.gs.com \n" +
"Component:\n" +
"Description: Client: ABC\n" +
"Server: ABCD\n" +
"Error: ABCDE Connection timed out\n" +
"Group: Group1\n" +
"Schedule: test\n" +
"Job: JobName\n" +
"Status: failed\n" +
"Level:\n" +
"Resolution: Please resolve";
Pattern regex = Pattern.compile("(?mi)^(?:Server:|Job:|Description: Client:)\\s*(.*)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
System.out.println(matcher.group(1));
}
<强>输出:强>
ABC
ABCD
JobName