Java Code 3 numeric characters (digits), excluding 000, 666 and any number in th
ID: 3843084 • Letter: J
Question
Java Code
3 numeric characters (digits), excluding 000, 666 and any number in the range of 900-999, followed by a hyphen, then 2 numeric characters (digits), followed by a hyphen and 4 numeric characters (digits).
Implement a regular expression as a Java String p like so:
String p = "*****************";
and use inside the match method:
public void match(String s) {
String p = "*****************";
System.out.println(s.matches(p)? "match " + s: "does not match " + s);
}
The test cases will invoke this method.
Example:
The following are valid identity numbers:
349-90-2839
694-12-0239
The following are invalid identity numbers:
666-29-8493
000-28-2323
912-38-2390
21-48-93043
Test Result match ("349-90-2839"); match 349-90-2839 match ("694-12-0239"); match 694-12-0239 match ("666-29-8493" does not match 666-29-8493 match ("000-28-2323" does not match 000-28-2323 match ("912-38-2390" does not match 912-38-2390 match ("21-48-93043" does not match 21-48-93043Explanation / Answer
Hi,
You can use this regex " ^(?!000|666|9d{2})d{3}-d{2}-d{4}$ "
Let me break it down for you.
^ asserts position at start of the string
Negative Lookahead
(?!000|666|9d{2})
Assert that the Regex below does not match the following 3 cases, seperated by |
1st Alternative
000
000 matches the characters 000 literally (case sensitive)
2nd Alternative
666
666 matches the characters 666 literally (case sensitive)
3rd Alternative
9d{2}
9 matches the character 9 literally (case sensitive)
d{2}
matches a digit (equal to [0-9])
{2} Quantifier — Matches exactly 2 times
d{3}
matches a digit (equal to [0-9])
{3} Quantifier — Matches exactly 3 times
- matches the character - literally (case sensitive)
d{2}
matches a digit (equal to [0-9])
{2} Quantifier — Matches exactly 2 times
- matches the character - literally (case sensitive)
d{4}
matches a digit (equal to [0-9])
{4} Quantifier — Matches exactly 4 times
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
Now, implementing in java using the above regex
Hope this is clear, let me know if you have any questions.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.