简体   繁体   中英

Javascript Regex to Java regex

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;
        }
        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?

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 (eg a{3,5} repeats a 3-5 times), and needs to be escaped in Java regexes.

Use this:

Pattern.compile("^08[3-9]-([0-9]){7}$");

Or even:

Pattern.compile("08[3-9]-([0-9]){7}");

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}\}?)$"; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM