Which statements are true about the following program?.
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { System.out.println(Pattern.matches("+?\d", "+2007")); // (1) System.out.println(Pattern.matches("+?\\d+","+2007")); // (2) System.out.println(Pattern.matches("\+?\\d+", "+2007")); // (3) System.out.println(Pattern.matches("\\+?\\d+", "+2007")); // (4) } }
Select the two correct answers.
(c) and (e)
To escape any metacharacter in regex, we need to specify two backslashes (\\) in Java strings.
A backslash (\) is used to escape metacharacters in both Java strings and in regular expressions.
In (1), the compiler reports that \d is an invalid escape sequence in a Java string.
(2) will throw a java.util.regex.PatternSyntaxException: dangling metacharacter +, which is the first character in the regex, is missing an operand.
In (3), the compiler reports that \+ is an invalid escape sequence.
(4) will match a positive integer with an optional + sign, printing true.
The method Pattern.matches()
returns true if the regex matches the entire input.