0

I have the following regex:

String regexContact = "^([0|\\+[0-9]{1,5})?([7-9][0-9]{9})$";

Android is pointing error at the end of the regex, saying:

Unclosed character class.

I have sifted through similar questions but could not find an answer for this particular error in my case. I am unable to find out if my regex itself is wrong somewhere. Any help would be appreciated.

2
  • 3
    Your first square bracket is not closed correctly. Commented Sep 1, 2016 at 7:03
  • What is the format of strings you want to match? I think you just need to remove the first [ as it is just erroneous as it starts a character class. Commented Sep 1, 2016 at 7:09

2 Answers 2

1
^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$
 ^↑    ^___^     ^ ^^___^^___^   ^
 |_______________| |_____________|

This first [ is not closed, if you want to match it literally, you should escape it: \\[, otherwise you should close it with a corresponding ].

Sign up to request clarification or add additional context in comments.

Comments

0

In Java regex flavor, the [ and ] symbols should be escaped inside a character class to denote literal symbols.

You have [0|\\+[0-9], where a [ is not escaped, and is considered a starting point for a character class, making the first [ unpaired, hence the error.

You need to remove the first [

String pat = "^(0|\\+[0-9]{1,5})?([7-9][0-9]{9})$";
               ^^

so as to match:

  • ^ - start of string
  • (0|\\+[0-9]{1,5})? - an optional group matching 1 or 0 occurrences of
    • 0 - a zero
    • | - or
    • \+[0-9]{1,5} - a plus symbol and any 1 to 5 digits
  • ([7-9][0-9]{9}) - Group 2 matching a 7, 8 or 9 and then any nine digits (these parentheses here can be removed)
  • $ - up to the end of string.

See the regex demo

Comments

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.