[英]Match everything before a pattern including including new line and/or carriage return
在遇到特定的群体之前,我该如何匹配所有事物
比赛:
第一组:
abc def xyz what ever foo blah blah keep matching this and this
Group 2:
01 Feb 2018 blah blah blah keep matching this and this keep matching this and this
组3: 01 Mar 2018 blah blah blah
3 01 Mar 2018 blah blah blah
从:
abc def xyz what ever foo blah blah keep matching this and this 01 Feb 2018 blah blah blah keep matching this and this keep matching this and this 01 Mar 2018 blah blah blah
在01 Jan 2018
日之前匹配所有内容,此处的日期为格式([0-9]{2}\\s[A-Za-z]{3}\\s[0-9]{4})
这似乎不起作用^((.*)(?!([0-9]{2}\\s[A-Za-z]{3}\\s[0-9]{4})))
您可以将此正则表达式与lookahead和DOTALL
修饰符一起使用:
(?ms)(.+?(?=^\d{2}\s[A-Za-z]{3}\s\d{4}|\z))
描述:
(?ms)
:启用DOTALL
修饰符,以便我们可以使用匹配包括换行符在内的任何字符.
。 同时启用MULTILINE
模式,以能够^
和$
锚。 .+?
:匹配1个或多个字符,包括换行符 (?=^\\d{2}\\s[A-Za-z]{3}\\s\\d{4})
:使用前瞻性断言确保我们有一个提前的日期(采用dd-mon-yyyy
格式) 码:
final String regex = "(?ms)(.+?(?=^\\d{2}\\s[A-Za-z]{3}\\s\\d{4}|\\z))";
final Pattern pattern = Pattern.compile( regex );
final Matcher matcher = pattern.matcher( input );
while (matcher.find()) {
System.out.println("Match: " + matcher.group(0));
}
我知道您现在要做什么。
为了避免复杂化,需要进行类似这样的操作。
"(?s)(?=.)([0-9]{2}\\\\s[A-Za-z]{3}\\\\s[0-9]{4})?.*?(?=(?:[0-9]{2}\\\\s[A-Za-z]{3}\\\\s[0-9]{4})|\\\\z)"
https://regex101.com/r/xGmVGp/1
可读的正则表达式
(?s) # Dot-all modifier
(?= . ) # Must be a char ahead (avoid empty string)
( # (1 start), Optional date at the start
[0-9]{2} \s
[A-Za-z]{3} \s
[0-9]{4}
)? # (1 end)
.*? # Optional , non-greedy any amount of characters
(?= # Assertion
(?: # Must be a date ahead (new record)
[0-9]{2} \s
[A-Za-z]{3} \s
[0-9]{4}
)
| # or,
\z # End of string
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.