0

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

3
  • 1
    [\\*] 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. Commented Sep 11, 2018 at 23:51
  • 1
    When using matches(), the $ pattern is redundant. Commented Sep 11, 2018 at 23:52
  • @Andreas Yes, you are right. Thanks. It is now working with [a-zA-Z0-9]*[*]? Commented Sep 11, 2018 at 23:57

1 Answer 1

3

You have to specify that the trailing asterisk is optional by using a ?

[a-zA-Z0-9]*[*]?
Sign up to request clarification or add additional context in comments.

4 Comments

It worked, thanks. But I also wanted regular expression to return true for *. I have edited my question now
Updated to check for 0 or more alphanumerics (*) instead of 1 or more (+).
Should be just [a-zA-Z0-9]*\\*? (or [a-zA-Z0-9]*[*]?), i.e. no need for both \\ and [], and no need for $.
Good point here and in question comments. Updated to remove escaping and terminal ($) check. @Andreas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.