I am trying to write regular expression in java to match alphanumeric string which can optionally have *. But if it contains * then it has to be at the end of that string. It can only contain one *
Below inputs should return true
abcd
abcd*
*
Where as below input should return false since it contains * which is not at the end of that string
abc*d
abcd**
I tried writing java program as shown below , but it is not working
public static void main(String[] a){
String pattern = "[a-zA-Z0-9]+[\\*]$";
String test = "abcd*";
System.out.println(test.matches(pattern));
}
It return true for abcd* but not for abcd and *
Please let me know how to fix this regular expression. Thanks
[\\*]is redundant. Either use a character class so*has no special meaning ([*]), or use escape so*has no special meaning (\\*). Doing both works, but is excessive.matches(), the$pattern is redundant.