我怎样才能带到统一格式的电话。数?仅使用正则表达式
可以是+79998887766或8999 8887766或8- 999 -888-77-66等。
但我只需要+7 999 888-77-66
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("Input your phone number: ");
Scanner in = new Scanner(System.in);
String number = in.nextLine();下一步是什么?
发布于 2020-01-22 01:58:01
给定三种不同格式的手机号码,您可以将其重新格式化为您提到的常见格式+7 999 888-77-66,方法是首先使用以下正则表达式将号码捕获为五组数字,
^\D*(\d)\D*(\d{3})\D*(\d{3})\D*(\d{2})\D*(\d{2})\D*$然后将其替换为
+$1 $2 $3-$4-$5将号码恢复为所需格式。
Java代码演示
List<String> numbers = Arrays.asList("+79998887766", "8 999 8887766", "8-999-888-77-66");
numbers.forEach(x -> {
System.out.println(x + " --> " + x.replaceAll("^\\D*(\\d)\\D*(\\d{3})\\D*(\\d{3})\\D*(\\d{2})\\D*(\\d{2})\\D*$", "+$1 $2 $3-$4-$5"));
});输出,
+79998887766 --> +7 999 888-77-66
8 999 8887766 --> +8 999 888-77-66
8-999-888-77-66 --> +8 999 888-77-66https://stackoverflow.com/questions/59846543
复制相似问题