N
N
Niki212122022-03-19 15:45:10
Java
Niki21212, 2022-03-19 15:45:10

How can I change the code so that it passes the regular expression test?

Implement the removal of extra characters when entering a phone number in the console and checking that the number matches the Russian mobile number format. If the entered string cannot be converted to the format of a mobile number, display a message about incorrect input. The phone can be entered not only in the format 79091234567, but also with extra characters.
The task involves the use of regular expressions. The code passes all required tests, but the regular expression test fails.

public class PhoneCleanerRegex {

  public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    while (true) {
      String input = scanner.nextLine();
      if (input.equals("0")) {
        break;
      }
      //TODO:напишите ваш код тут, результат вывести в консоль.


    input = input.replaceAll("[^0-9]", "");
    if (Pattern.matches("^7[0-9]{10}$", input)) {
      System.out.println(input);
    } else if (Pattern.matches("^8[0-9]{10}$", input)) {
      System.out.println("7" + input.substring(1));
    } else if (Pattern.matches("^[0-9]{10}$", input)) {
      System.out.println("7" + input);
    } else {
      System.out.println("Неверный формат номера");
    }
  }
}
}


How can the code be modified to test for regular expressions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PavelMos, 2022-03-19
@PavelMos

Which lines i.e. phone numbers don't work?
Instead of numbers, it's easier to write /D - any non-digit or /d any digit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question