Created
February 4, 2019 09:24
-
-
Save jflopezfernandez/4870ad97439bfa3c490a0fe59552fd6c to your computer and use it in GitHub Desktop.
Parsing phone numbers in Java with regular expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.regex.*; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
List<String> PhoneNumbers = new ArrayList<String>(); | |
PhoneNumbers.add("(813)929-7253"); | |
PhoneNumbers.add("954-344-7183"); | |
PhoneNumbers.add("1-954-355-2342"); | |
PhoneNumbers.add("1(201) 444-3824"); | |
String RegexPhoneNumber = "[( ]*(?<AreaCode>[0-9]{3})[-) ]+(?<Prefix>[0-9]{3})[-) ]+(?<LineNumber>[0-9]{4})"; | |
Pattern pattern = Pattern.compile(RegexPhoneNumber); | |
for (String PhoneNumber : PhoneNumbers) { | |
Matcher matcher = pattern.matcher(PhoneNumber); | |
if (matcher.find()) { | |
System.out.printf("Area Code: %s\n", matcher.group("AreaCode")); | |
System.out.printf("Prefix: %s\n", matcher.group("Prefix")); | |
System.out.printf("Line Number: %s\n", matcher.group("LineNumber")); | |
System.out.println("\n\n"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment