Hi, Im trying to match patterns to get A-F and number range 0-9

So like 9D

4EEE

Not 15d

heres the code i have got so far

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class sam {

	public static void main (String [] args){
		//instantiate scanner
		Scanner s = new Scanner(System.in);
		//print
		System.out.println("Please enter hex");
		//assign input to String
		String a=s.next();
		//if it can find pattern
       if(a.matches("([a-fA-F0-9]*)")){
    	   // 
    	  System.out.println("right");
       }
       else
    	   
		do{
			//we then ask for the user input if it is not valid
			System.out.println("Not valid enter again:");
			//assign input to string a
			a = s.next();
			//check if it matches pattern
		}
		//while it cannot find pattern in String or ineger value is higher than 10
		while(!a.matches("([a-fA-F0-9]*)"));
	}
}

Hi, Im trying to match patterns to get A-F and number range 0-9

So like 9D

4EEE

Not 15d

I cannot make any reasonable guess from that on what sort of string should be accepted and what not !!!
But in either case your regular expression (regex) is incorrect, the "*" quantifier suggests that the mentioned pattern may occur zero or more times, so even a blank string would match your regex, if you want to test for a hexadecimal value, I suggesting changing the "*" to a "+" which implies the given pattern appear at least once.

You can see this tutorial to get a solid understanding about regular expressions in Java.

Edited 6 Years Ago by stephen84s: n/a

This article has been dead for over six months. Start a new discussion instead.