Aleksei Nikolaevich
Aleksei Nikolaevich

Reputation: 325

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();

Upvotes: 4

Views: 6776

Answers (3)

hwnd
hwnd

Reputation: 70722

@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

Upvotes: 2

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

Simple use: (?:\\n|$), so your regular expression becomes:

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

Upvotes: 5

ppeterka
ppeterka

Reputation: 20726

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

Upvotes: 2

Related Questions