My app is passing in a user id. We're hard coding 4 users.
user01
user03
user05
user07
We have validation that the user passed in is one of these.
private void validateUser(String userId) {
if (!userId.matches("(user0)[1|3|5|7]")) {
throw new SecurityException("Invalid user");
}
}
This seems to work but Sonarlint flags the regex string with "Remove duplicates in this character class". Is there a better way to write the same thing?
I see. I don't know who came up with that. Apparently the | was supposed to mean "or" but that's already the purpose of the [].if (!userId.matches("(user0)[1|3|5|7]")) {First, try logging in as "user0|". Then ponder what happens. Then lose the "|" characters.
throw new SecurityException("Invalid user");
}
}
This seems to work but Sonarlint flags the regex string with "Remove duplicates in this character class". Is there a better way to write the same thing?
(You may also want to lose the "(" and ")", as they seem purposeless.)
I see. I don't know who came up with that. Apparently the | wasif (!userId.matches("(user0)[1|3|5|7]")) { throw newFirst, try logging in as "user0|". Then ponder what happens. Then
SecurityException("Invalid user"); } } This seems to work but
Sonarlint flags the regex string with "Remove duplicates in this
character class". Is there a better way to write the same thing?
lose the "|" characters. (You may also want to lose the "(" and
")", as they seem purposeless.)
supposed to mean "or" but that's already the purpose of the [].
regex101 says the () makes a capturing group which matches the
characters literally (case sensitive), apparently it does the same
thing without the () but doesn't call it a capturing group. so just .matches("user0[1357]")
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 388 |
Nodes: | 16 (2 / 14) |
Uptime: | 08:51:46 |
Calls: | 8,221 |
Files: | 13,122 |
Messages: | 5,872,550 |