Given the following code:.
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String[] regexes = {// w w w . jav a 2 s . c o m "(-|+)\\d+", "(-|+)?\\d+", "(-|\\+)\\d+", // 0, 1, 2 "(-|\\+)?\\d+", "[-+]?\\d+", "[-+]?[0-9]+", // 3, 4, 5 "[-\\+]?\\d+" }; // 6 // (1) INSERT DECLARATION STATEMENT HERE System.out.println(Pattern.matches(regexes[i], "2007")); System.out.println(Pattern.matches(regexes[i], "-2007")); System.out.println(Pattern.matches(regexes[i], "+2007")); } }
Which declarations, when inserted independently at (1), will make the program print:.
true true true
Select the four correct answers.
(d), (e), (f), and (g)
(a), (b) A java.util.regex.PatternSyntaxException is thrown because the first + in the regex is a dangling metacharacter.
(c) The regex does not match the target "2007", since a sign is required.
The regex (-|\\+)? and [-+]? are equivalent: 0 or 1 occurrence of either - or +.
Note that in the [] regex notation, the + sign is an ordinary character as in (e) and (f), and escaping it as in (g) is not necessary.
The metacharacter \d is equivalent to [0-9], i.e., any digit.