简体   繁体   中英

How to specify new line OR the end of string in regex?

My Pattern does not work well for all strings because in case it gets to the string that has no further new line \\n it would throw an exception. How can I modify (?:L.*?)\\\\n so that it will match until \\\\n OR the end of the String?

Pattern patternL = Pattern.compile("(?:L of .*?)\\n", Pattern.DOTALL);
Matcher matcherL = patternL.matcher(text);
matcherL.find();

简单使用: (?:\\\\n|$) ,所以你的正则表达式变为:

Pattern patternL = Pattern.compile("(?:L of .*?)(?:\\n|$)", Pattern.DOTALL);

For Java, this is what you need to match the end of the line or a single LF character:

(\\n|$)

Or perhaps

(\\r\\n|\\n|$)

If you want to be precise about the line break, and include CRLF too

@Sniffer's answer on matching line break or end of line is correct, but from the code that you posted above (?:L of .*?) , this will not match for Location or for that matter any word, except for the letter L

Pattern patternL = Pattern.compile("Location of .*?(?:\\n|$)", Pattern.DOTALL);

Pattern.MULTILINE tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string).

Pattern patternL = Pattern.compile("^Location of .*", Pattern.MULTILINE);

I went from a non-greedy to greedy match above to match the most amount possible , using a non greedy match will match the least amount possible unless you use an end of line anchor $

See what I mean by matching least amount possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM