4

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?

3 Answers 3

3

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 the DOTALL flag is specified.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

You need to add the flag Pattern.DOTALL. By default, . does not match line terminators.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.