Regex的新手,我相信我正在为Java开发正则表达式,但有一个问题是行中有回车符,这使得(.*)
(最后一组)与换行符匹配。
^([0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}(?:,[0-9]{3})?)\s(?:\^\[\[[0-9]{2}m)\[([A-Za-z]+)\](?:\^\[\[m)\s*([0-9a-fA-F\-]*)\s\(([^\)]+)\)\s((?:[a-zA-Z0-9-]+\.)+[A-Za-z0-9$]+):\s(?:\s\-\s)?(.*)
不匹配第一行之后的两行,但选择了第四行
02 Jan 2018 05:25:56,546 ^[[32m[TEXT]^[[m aabb33-ddee33-54321 (host-1-usa-east) this.is.sample.log: service is responding normal
extra line 1
extra line 2
03 Jan 2018 08:25:56,546 ^[[32m[TEXT]^[[m aabb33-ddee33-54321 (host-1-usa-east) this.is.sample.log: service is responding normal
有没有一种方法可以使所有这些与回车符相匹配。
更新:
正则表达式后面不是最后一个组
^([0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}(?:,[0-9]{3})?)\s(?:\^\[\[[0-9]{2}m)\[([A-Za-z]+)\](?:\^\[\[m)\s*([0-9a-fA-F\-]*)\s\(([^\)]+)\)\s((?:[a-zA-Z0-9-]+\.)+[A-Za-z0-9$]+):(?:\s\-\s)?(?:(?!^[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*(?:\r?\n)?)*
Service is responding normal
Test results 1 = True
Test results 2 = "{False}"
10 Aug 2018 06:00:02,152 ^[[32m[TEST]^[[m aabb345-397c-4656 (host-1-usa-east) this.is.sample.log: Service is responding normal
Test results 1 = True
Test results 2 = "{False}"
10 Aug 2018 06:00:02,152 ^[[32m[TEST]^[[m aabb345-397c-4656 (host-1-usa-east) this.is.sample.log: Service is responding normal
答案 0 :(得分:1)
您可以按照Sebastian Proske的建议,用(.*)
将最后一个(?:(?!^[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}).*(?:\r?\n)?)*
替换为(?!
,后者使用否定的前瞻性(?:
来断言所遵循的不是您在自己指定的模式regex和匹配任何字符,直到字符串结尾,并匹配可选的换行符。
替换零件的说明
(?!
非捕获组
^[0-9]{2}\s[A-Za-z]{3}\s[0-9]{4}\s[0-9]{2}:[0-9]{2}:[0-9]{2}
负向超前
).*
与字符串开头匹配的模式(?:\r?\n)?
结束负向查找,并匹配零个或更多次任何字符)*
匹配可选的换行符Map<String, Double> txAmountByMedium = transactions.stream()
.collect(Collectors.groupingBy(Transaction::getMedium,
Collectors.summingDouble(Transaction::getAmount)));
关闭非捕获组并重复零次或更多次您的正则表达式可能如下: