Reputation: 1
Here is the code !
private boolean isIdCorrect(String userIdToAdd) {
boolean checkValues = true;
if(userIdToAdd.length() == 18) {
if(userIdToAdd.charAt(0) == '#'
&& userIdToAdd.charAt(7) == '@') {
for(int i = 1 ; i < 7 ; i++) {
if(!((userIdToAdd.charAt(i) >= 'a'
&& userIdToAdd.charAt(i) <= 'f')
|| (userIdToAdd.charAt(i) >= '0'
&& userIdToAdd.charAt(i) <= '9'))) {
checkValues = false;
}
if(!checkValues) {
return false;
}
}
for(int i = 8 ; i < 18 ; i++) {
if(!((userIdToAdd.charAt(i) >= 'a'
&& userIdToAdd.charAt(i) <= 'f')
|| (userIdToAdd.charAt(i) >= '0'
&& userIdToAdd.charAt(i) <= '9'))) {
checkValues = false;
}
if(!checkValues) {
return false;
}
}
return true;
}
return false;
}
return false;
}
The goal is to return true if the String looks like #[6 char long hex string]@[8 char long hex string], else we return false.
Here is the regex : /#[0-9a-f]{6}@[0-9a-f]{8}/
As you can see it looks like dirty, but, it is really bad besides REGEX, in terms of performance ?
Thank you in (GameBoy) advance (SP) !
Upvotes: 0
Views: 72
Reputation: 89639
Note that when you have a code with a lot of nested loops and conditionals, the first reflex is to try to design it better, example:
private boolean isHexChar(char c) {
return (c > '/' && (c < ':' || c > '`' && c < 'g'));
}
private boolean isIdCorrect(String userIdToAdd) {
if( userIdToAdd.length() != 18 || userIdToAdd.charAt(0) != '#' || userIdToAdd.charAt(7) != '@') {
return false;
}
for(int i=1; i<7; i++) {
if (!isHexChar(userIdToAdd.charAt(i))) {
return false;
}
}
for(int i=8; i<18; i++) {
if (!isHexChar(userIdToAdd.charAt(i))) {
return false;
}
}
return true;
}
Once done you can try to compare the speed with a regex (if you think it's important), but note that now the situation is different since you have a more readable (and probably faster) code.
Upvotes: 0
Reputation: 1248
There are a few reasons why you should probably use a regex.
Upvotes: 3