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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With