1

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?

3 Answers 3

1

Use this:

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

Or even:

Pattern.compile("08[3-9]-([0-9]){7}");
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. You might want to get a regular expression cheat sheet next time you work with regular expressions. Also try using baregrep.
1

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.

2 Comments

You need two \ to escape it. To be fair, some regex engines take the {} literally if the are not used in this {n,n} format.
Sorry, I fell asleep! I'm in work now, but will be back to it later... I'll report back then
0

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

1 Comment

Hi, when I use that pattern, I get this error: Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.