Reputation: 619
I am trying to create a hexadecimal calculator but I have a problem with the regex
.
Basically, I want the string to only accept 0-9
, A-E
, and special characters +-*_
My code keeps returning false no matter how I change the regex, and the adding the asterisk is giving me a PatternSyntaxException
error.
public static void main(String[] args) {
String input = "1A_16+2B_16-3C_16*4D_16";
String regex = "[0-9A-E+-_]";
System.out.println(input.matches(regex));
}
Also whenever I add the *
as part of the regex it gives me this error:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 9
[0-9A-E+-*_]+
^
Upvotes: 0
Views: 340
Reputation: 59
public static boolean isValidCode (String code) {
Pattern p = Pattern.compile("[fFtTvV\\-~^<>()]+"); //a-zA-Z
Matcher m = p.matcher(code);
return m.matches();
}
Upvotes: 0
Reputation: 31439
You need to match more than one character with your regex. As it currently stands you only match one character.
To match one or more characters add a +
to the end of the regex
[0-9A-E+-_]+
Also to match a *
just add a star in the brackets so the final regex would be
[0-9A-E+\\-_*]+
You need to escape the -
otherwise the regex thinks you want to accept all character between +
and _
which is not what you want.
Upvotes: 3
Reputation: 136062
You regex is OK there should be no exceptions, just add +
at the end of regex which means one or more characters like those in brackets, and it seems you wanted *
as well
"[0-9A-E+-_]+"
Upvotes: 1