So, I have to write an Regex statement which proofs if a number is dividable by 5 and returns either true or false. So, after some research I found out that any number which ends with a 0 or 5 is dividiable by 5 and therefore I try to match the last digit of the string with either a 0 or 5.
However, it does not seem to work as the method only returns false, although it worked on an online regex checker.
public class MyClass {
public static void main(String args[]) {
String[] digits = {"20", "25", "000", "001", "5123456789"};
for (String s : digits){
System.out.println("\"" s "\"" " -> " proof(s));
}
}
public static boolean proof(String s){
return s.matches("[0|5]$"); // Here is somehow an issue.
}
}
CodePudding user response:
Here's one of the possible ways to implement this:
public static boolean proof(String s) {
return s.matches("([1-9]\\d*)?[05]");
}
Where ([1-9]\\d*)?
matches an optional group of characters (i.e. it might not be present) which should start with a digit from 1
to 9
followed by zero or more digits.
Note
Pipe symbol
'|'
is not needed. When you're using square brackets[]
, you only need to enumerate the symbols you need to match, i.e.[05]
.While using
matches()
regular expression would be applied to the whole string, i.e. neither^
and the very beginning, no$
at the very end are not needed.Disclaimer: in my interpretation of the problem statement leading zeros are not allowed. If this requirement is not relevant, then the following regular expression would be sufficient:
"\\d*[05]"
.
To avoid compiling this regular expression at each method call, we can extract it into static
final
field. And since you need a boolean
result it would be convenient to keep it as a Predicate
, for that we can make use of Java 11 Pattern.asMatchPredicate()
public static final Predicate<String> IS_DIVISIBLE_BY_FIVE =
Pattern.compile("([1-9]\\d*)?[05]").asMatchPredicate();
public static boolean proof(String s) {
return IS_DIVISIBLE_BY_FIVE.test(s);
}
main()
public static void main(String[] args) {
String[] digits = {"20", "25", "000", "001", "5123456789"};
for (String number : digits) {
System.out.println(number " -> " proof(number));
}
}
Output:
20 -> true
25 -> true
000 -> false
001 -> false
5123456789 -> false