Java regular expression matching problem?

I want to write a regular expression that matches the following five format strings:
1. Number
2. Number-sharp
3. Number-sharp-sharp
4. Number-sharp*
5. Digits-sharp digits

question: how to write regular expressions that match the format strings in these 5? Please give me your advice.

I try to use [0-9] +-sharp | * | [0-9] and other matching methods are not allowed

    public static boolean checkAccount(String email){
        boolean flag = false;
        try{
            String check = "[0-9]+-sharp|*|[0-9]";
//            String check = "\\d-sharp|*|[0-9]";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        }catch(Exception e){
            flag = false;
        }
        return flag;
    }
//    +-sharp|-sharp-sharp|-sharp*+
    public static void main(String[] args) {
        System.out.println(checkAccount("12334-sharp"));
        System.out.println(checkAccount("12334-sharp-sharp"));
        System.out.println(checkAccount("12334-sharp*"));
        System.out.println(checkAccount("12334-sharp12367"));
        System.out.println(checkAccount("123123"));
    }
Mar.02,2021

^\d+(-sharp([*-sharp]|\d+))?$

match results see here

Code:

public static boolean checkAccount(String input){
        return Pattern.matches("^\\d+(?:-sharp?\\d*|-sharp[-sharp*])$", input);
    }

if you want to match a string that meets the above rules in a piece of text, use:

\d+(-sharp(-sharp|\*|\d+)?)?

or, according to your habit, replace \ d with [0-9] :

[0-9]+(-sharp(-sharp|\*|[0-9]+)?)?

if you want to verify that a string conforms to the rule, it is best to use:

^\d+(-sharp(-sharp|\*|\d+)?)?$

Note : the above are pure rules. If you want to use them in various languages, remember to change the meaning of some characters. For example, the character \ should be changed in java. It should look like this:

String check = "^\\d+(-sharp(-sharp|\\*|\\d+)?)?$";

I have verified the above rule, but the above java has not been measured. If it is not correct, let's see which character needs to be changed.

Menu