Reputation: 740
On running this program,
import java.util.regex.*;
public class PatternExample {
public static final String numbers = "1\n22\n333\n4444\n55555\n666666\n7777777\n88888888\n999999999\n0000000000";
public static void main(String[] args) {
Pattern pattern = Pattern.compile("9.*", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(numbers);
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
}
}
Output is
Start index: 44 End index: 53 999999999
I expected the output include the zeros, because of Pattern.MULTILINE
.
What should I do to include the zeros?
Upvotes: 4
Views: 89
Reputation: 34618
You need to add the flag Pattern.DOTALL
. By default, .
does not match line terminators.
Upvotes: 2
Reputation: 13640
You are looking for Pattern.DOTALL
, use the following:
Pattern pattern = Pattern.compile("9.*", Pattern.DOTALL);
Also Pattern.MULTILINE
is not necessary here since you are not using any start ^
and end $
anchors.
Upvotes: 2
Reputation: 328588
You need to add the DOTALL
flag (and don't need the MULTILINE
flag which only applies to the behaviour of ^
and $
):
Pattern pattern = Pattern.compile("9.*", Pattern.DOTALL);
This is stated in the javadoc
The regular expression
.
matches any character except a line terminator unless theDOTALL
flag is specified.
Upvotes: 3