0

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+-*_]+
         ^
4

3 回答 3

3

您需要将多个字符与您的正则表达式匹配。按照目前的情况,您只能匹配一个字符。

要匹配一个或多个字符+,请在正则表达式的末尾添加一个

[0-9A-E+-_]+

还要匹配 a*只需在括号中添加一个星号,以便最终的正则表达式为

[0-9A-E+\\-_*]+

您需要转义,-否则正则表达式认为您想要接受之间的所有字符,+_这不是您想要的。

于 2013-05-06T03:27:02.280 回答
1

你的正则表达式没问题,应该没有例外,只需+在正则表达式的末尾添加一个或多个字符,如括号中的字符,看起来你也*想要

"[0-9A-E+-_]+"
于 2013-05-06T03:27:46.033 回答
0
public static boolean isValidCode (String code) {
    Pattern p = Pattern.compile("[fFtTvV\\-~^<>()]+"); //a-zA-Z
    Matcher m = p.matcher(code);
    return m.matches();
}
于 2018-03-07T19:08:41.247 回答