Reputation: 53657
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
Reputation: 56915
Characters like |*.[](){}?+^$
have special meaning in regex. Use [\^*]
(within a []
only ]
and -
have special meaning), or escape them like ^(\*|\^)
.
Upvotes: 3
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
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