-4

I am trying to create a regex where I get the results as +82 11-1111-1111 in java. The first number should start with +82 with a space then it should get accept only 11 or 12 or 13 and the n the rest of the numbers can accept numbers between 0-9

For eg.

  1. +82 12-2234-3344
  2. +82 13-1234-5678
  3. +82 11-3456-4567

Please help

Akshay
  • 351
  • 1
  • 2
  • 19

1 Answers1

1

I think you should try something like this:

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

public class PhoneNumberRegex {
    public static void main(String[] args) {
        System.out.println(validate("+82 12-2234-3344"));
        System.out.println(validate("+82 13-1234-5678"));
        System.out.println(validate("+82 11-3456-4567"));
        System.out.println(validate("+82 31-3456-4567"));
        System.out.println(validate("+82 31-34564-4567"));
    }
    
    private static boolean validate(String input) {
        Pattern argPattern = Pattern.compile("\\+82 (12|13|11)(?:-\\d{4}){2}");
        Matcher matcher = argPattern.matcher(input);
        return matcher.matches();
    }
}

When I run this, I get this output:

src : $ java PhoneNumberRegex 
true
true
true
false
false
Rohan Kumar
  • 4,060
  • 6
  • 23
  • 33