I have the following regex in Javascript:
/^(\{?(08)([3-9]){1}-([0-9]){7,7}\}?)$/
It matches numbers like:
087-1234893, 083-2839283, 086-4283944, etc.
I've converted it to Java (Android) as follows:
public boolean isValidMobilePhone(String phone){
boolean returnObj=false;
Pattern p = Pattern.compile("^({?(08)([3-9]){1}-([0-9]){7,7}}?)$");
Matcher m = p.matcher(phone);
boolean matchFound = m.matches();
if (matchFound){
returnObj=true;
开发者_JS百科 }
return returnObj;
}
Here is the error I get:
07-12 23:26:10.478: ERROR/AndroidRuntime(11464): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_RULE_SYNTAX near index 3: 07-12 23:26:10.478: ERROR/AndroidRuntime(11464): ^({?(08)([3-9]){1}-([0-9]){7,7}}?)$ 07-12 23:26:10.478: ERROR/AndroidRuntime(11464): ^ 07-12 23:26:10.478: ERROR/AndroidRuntime(11464): at com.ibm.icu4jni.regex.NativeRegEx.open(Native Method)
I can't figure out what's wrong with the third '?' character! I tried escaping it with '\', but that won't compile.
Can anyone please help me?
Use this:
Pattern.compile("^08[3-9]-([0-9]){7}$");
Or even:
Pattern.compile("08[3-9]-([0-9]){7}");
Escape the {
, and most likely the }
near the end as well.
Pattern p = Pattern.compile("^(\\{?(08)([3-9]){1}-([0-9]){7,7}\\}?)$");
The {
character is a special character used to repeat (e.g. a{3,5}
repeats a
3-5 times), and needs to be escaped in Java regexes.
need only remove the delimiters
for javascript:
var pattern = /^(\{?(08)([3-9]){1}-([0-9]){7,7}\}?)$/;
for Java:
string pattern = "^(\{?(08)([3-9]){1}-([0-9]){7,7}\}?)$";
精彩评论