0

I need user input for a hexadecimal number so as long as their input contains the characters A-F or 0-9 it won't re-prompt them.

This is what I have which runs as long as the inputed string contains A-F and or 0-9, it still runs if you add on other characters which I don't want.

do {
    System.out.print("Enter a # in hex: ");
    inputHexNum = keyboard.next();      
} while(!(inputHexNum.toUpperCase().matches(".*[A-F0-9].*")));
Edd
  • 3,724
  • 3
  • 26
  • 33
Nei Mina
  • 139
  • 1
  • 2
  • 6

3 Answers3

3

Could you not change your regex to be [A-F0-9]+?

So your code would look like the following:

do {
    System.out.print("Enter a # in hex: ");
    inputHexNum = keyboard.next();
} while(!(inputHexNum.toUpperCase().matches("[A-F0-9]+")));

As I understand the question, the problem with your current regex is that it allows any character to occur zero or more times, followed by a hex character, followed by any old character zero or more times again. This restricts the entire input to only containing at least one character that consists of the letters A-F (uppercase) and the digits 0-9.

Edd
  • 3,724
  • 3
  • 26
  • 33
2

Your regular expression probably doesn't do what you want. .* matches anything at all (empty string up to any number of arbitrary characters). Then you expect a single hex character followed again by anything.

So these would be valid inputs:

--0--
a
JFK

You should either say "I want a string which contains only valid hex digits. Then your condition would be:

while(!(inputHexNum.toUpperCase().matches("[A-F0-9]+")));

or you can check for any illegal characters with the pattern [^A-F0-9]. In this case, you'd need to create a Matcher yourself:

Pattern illegalCharacters = Pattern.compile("[^A-F0-9]");
Matcher matcher;
do {
    ...
    matcher = illegalCharacters.matches(inputHexNum.toUpperCase());
} while( matcher.find() );
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

The regular expression that you are using matches every string that contains at least one hex digit. Judging from the first paragraph of the question this is exactly what you want. This is because "." matches any character (but possibly not linebreaks), so ".*" matches any (possibly empty) sequence of characters. Thus the regex ".*[A-F0-9].*" means "first, some arbitrary characters, then a hex digit, then some more characters". But from the second paragraph of the question it looks like you want to use the regex "[A-F0-9]+" which means "some hex digits (but at least one, and nothing else)". I assume you are confused about what needs to be done, but actually want the second.