Java regex program does not work as expected

When 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

Start index: 44 End index: 53 999999999

I expected the output to include zeros due Pattern.MULTILINE. What should I do to include zeros?

+4
source share
3 answers

You need to add a flag DOTALL(and don't need a flag MULTILINEthat only applies to ^and behavior $):

Pattern pattern = Pattern.compile("9.*", Pattern.DOTALL);

This is indicated in javadoc

A regular expression .matches any character except a string terminator if a flag is not specified DOTALL.

+3
source

You are looking for Pattern.DOTALL, use the following:

Pattern pattern = Pattern.compile("9.*", Pattern.DOTALL);

Pattern.MULTILINE, ^ end $ .

+2

You need to add a flag Pattern.DOTALL. By default . does not match string terminators .

+2
source

All Articles