There is a variable (String) that contains some text, in any part of which there can be a phone number in the format + nnnnnnnnnnnn. A total of 12 numbers and a "+" at the beginning. How to allocate these 12 digits (or a string containing 12 digits and a “+” at the beginning) into a separate variable?
- Use regular expressions, a similar question with the answer here - stackoverflow.com/a/4662265/2082873 - Werder
|
2 answers
String s = "rgrg r +123456789876efgr"; Pattern p = Pattern.compile("\\+[0-9]{12}"); Matcher m = p.matcher(s); while (m.find()){ System.out.println(m.group()); // m.group твоя переменная } |
Since it is immediately known that all phone numbers will begin with "+375" and that there will be 12 digits - I found an alternative method:
String i1 = "yfhiyy yrgkytff +375338550935 hyffhjju"; //Проверка на наличие номера телефона в тексте boolean isContain = i1.contains("+375"); if (isContain) { //Вычисляем позицию знака "+" в строке int ant = i1.indexOf("+"); //Выводим 12 символов сразу после знака "+" String telefon = i1.substring(ant, ant+13); System.out.println("Номер телефона: " + telefon); } else { System.out.println("Номер телефона в строке не найден"); } - Use regular expressions for such problems, since it's faster and more readable - SergeiK
- Thank you for the information! - Vladimir
|