By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Match Phone Number - Java Task (RegEx)

+13 votes

Write a regular expression to match a valid phone number from Sofia. A valid number will start with "+359" followed by the area code (2) and then the number itself, consisting of 7 digits (separated in two group of 3 and 4 digits respectively). The different parts of the number are separated by either a space or a hyphen ('-'). Refer to the examples to get the idea.

  • Use quantifiers to match a specific number of digits
  • Use a capturing group to make sure the delimiter is only one of the allowed characters (space or hyphen) and not a combination of both. Use the group number to achieve this
  • Add a word boundary at the end of the match to avoid partial matches (the last example on the right-hand side: +359-2-222-22222)
  • Ensure that before the '+' sign there is either a space or the beginning of the string


Match ALL of these

Match NONE of these

+359 2 222 2222


359-2-222-2222, +359/2/222/2222, +359-2 222 2222

+359 2-222-2222, +359-2-222-222, +359-2-222-22222




+359 2 222 2222



+359 2 222 2222


+359 2 234 5678


+359-2 234-5678


+359 2 234 5678



asked in Java category by user hues

1 Answer

+1 vote
Best answer

Here's the solution.

Please note that you have to use word boundaries \b to get ONLY 4 numbers at the end of the phone number!

Also the group for the space(s) and the "-" looks like this: (\\s+|-) to refer to it later when checking use: (\\2) - the second group; Check line #10 for the actual regex;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pr_02_MatchPhoneNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(;

        String input;
        Pattern pattern = Pattern.compile("(\\+359)(\\s+|-)(2)(\\2)([\\d]{3})(\\2)([\\d]{4}\\b)");

        while (!(input = scanner.nextLine()).equals("end")) {
            Matcher matcher = pattern.matcher(input);
            if (matcher.find()) {
answered by user john7
edited by user golearnweb