What is dotall mode in regex Java?
Overview
When we use the dot . expression in regex, we match every character in an input string, except a newline character by default.
A line terminator will be included in the match if the Pattern.DOTALL flag is set. The embedded flag expression (?s) can also be used to activate dotall mode.
Code
How to use Pattern.DOTALL
DOTALL is a static constant defined in the Pattern class.
To enable dotall mode, we create an instance of the Pattern class using the compile() method, and pass the regex and Pattern.DOTALL constant.
In the code below, to run the pattern matching, we enable and disable the dotall mode.
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Main {private static void withoutDotall(String text){Pattern patternWithoutDotAll = Pattern.compile("(.*)");Matcher matcherWithoutDotAll = patternWithoutDotAll.matcher(text);boolean matched = matcherWithoutDotAll.find();if(matched){System.out.println("Matching without DOTALL - \"" + matcherWithoutDotAll.group(1) + "\"");}}private static void dotall(String text){Pattern patternWithDotAll = Pattern.compile("(.*)", Pattern.DOTALL);Matcher matcherWithDotAll = patternWithDotAll.matcher(text);boolean matched = matcherWithDotAll.find();if(matched){System.out.println("Matching with DOTALL - \"" + matcherWithDotAll.group(1) + "\"");}}public static void main(String[] args){String text = "educative is the best" + System.getProperty("line.separator") + " learning platform";withoutDotall(text);dotall(text);}}
How to use embedded flag expression
Embedded flag expressions, as the name indicates, are embedded in the regular expressions themselves. (?s) is the embedded flag expression to enable the dotall mode.
import java.util.regex.Matcher;import java.util.regex.Pattern;public class Main {private static void withoutDotall(String text){Pattern patternWithoutDotAll = Pattern.compile("(.*)");Matcher matcherWithoutDotAll = patternWithoutDotAll.matcher(text);boolean matched = matcherWithoutDotAll.find();if(matched){System.out.println("Matching without DOTALL - \"" + matcherWithoutDotAll.group(1) + "\"");}}private static void dotallEmbedded(String text){Pattern patternWithDotAll = Pattern.compile("(?s)(.*)");Matcher matcherWithDotAll = patternWithDotAll.matcher(text);boolean matched = matcherWithDotAll.find();if(matched){System.out.println("Matching with DOTALL - \"" + matcherWithDotAll.group(1) + "\"");}}public static void main(String[] args){String text = "educative is the best" + System.getProperty("line.separator") + " learning platform";withoutDotall(text);dotallEmbedded(text);}}