Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53657

How to check if a number starts with Special Characters using regular expression

Using following regexp I can get if a string starts with a or b.

        Pattern p = Pattern.compile("^(a|b)");
        Matcher m = p.matcher("0I am a string");
        boolean b = m.find();
        System.out.println("....output..."+b);

But I need to check if the string starts with some special characters like * or ^ etc. In that case the following regexp gives Pattern error.

Pattern p = Pattern.compile("^(*|^)");
        Matcher m = p.matcher("0I am a string");
        boolean b = m.find();

        System.out.println("....output..."+b);

How to check if a number starts with * or ^ using regular expression

Upvotes: 1

Views: 12802

Answers (5)

mathematical.coffee
mathematical.coffee

Reputation: 56915

Characters like |*.[](){}?+^$ have special meaning in regex. Use [\^*] (within a [] only ] and - have special meaning), or escape them like ^(\*|\^).

Upvotes: 3

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53657

Thanks to mathematical.coffee for nice response

Finally I found a solution by using ^[*^] as regexp to test whether a string contains * or ^

Source Code

Pattern p = Pattern.compile("^[*^]");
        Matcher m = p.matcher("I am a string");
        boolean b = m.find();

        System.out.println("....output..."+b);

Upvotes: 0

Sufian Latif
Sufian Latif

Reputation: 13356

You can try '(\^|\*)[0-9]+' for the purpose.

Since both ^ and * are special characters in regex, you'll need to put \ before them.

If you wish that the whole string must match with it, put the regex between ^ and $.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425043

Use this:

"0I am a string".matches("[\\^*].*");

Upvotes: 0

Deco
Deco

Reputation: 3321

* and ^ are special characters in regex which need to be escaped, so you will need to use a \ to escape it.

See this link for more information.

Upvotes: 1

Related Questions