Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * You are given a string, holding ASCII characters.
- * Find all name -> phone number pairs, format them and print them in an ordered list as list items.
- * The name should be at least one letter long, can contain only letters and should always start with an uppercase letter.
- * The phone number should be at least two digits long, should start and end with a digit (optionally, there might be a “+” in front)
- * and might contain the following symbols in it: “(“, “)”, “/”, “.”, “-”, “ “ (left and right bracket, slash, dot, dash and whitespace).
- * Between a name and the phone number there might be any number of symbols, other than letters and “+”.
- * Between the name -> phone number pairs there might be any number of ASCII symbols.
- * The output format should be <b>[name]:</b> [phone number] (there is one space between the name and the phone number).
- * Clear any characters other than digits and “+” from the number when printing the output.
- * The Input will be read from the console. It will consist of several lines holding the input string.
- * The command "END" denotes the end of input.
- * The Output should hold the resulting Ordered List (on a Single line), or a Single Paragraph, holding “No matches!”
- */
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class PhoneNumbers {
- public static void main(String[] args) {
- StringBuilder inputText = new StringBuilder();
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
- String inputLine = reader.readLine();
- while (!inputLine.equals("END")) {
- inputText.append(inputLine);
- inputLine = reader.readLine();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- Pattern pattern = Pattern.compile("([A-Z][a-zA-Z]*)[^+a-zA-Z]*?(\\+?\\d[-./()0-9 ]*\\d)");
- Matcher matcher = pattern.matcher(inputText.toString());
- boolean isMatch = matcher.find();
- if (isMatch) {
- System.out.print("<ol>");
- while (isMatch) {
- System.out.printf("<li><b>%s:</b> %s</li>",
- matcher.group(1), matcher.group(2).replaceAll("[^+\\d]+", ""));
- isMatch = matcher.find();
- }
- System.out.print("</ol>");
- } else {
- System.out.println("<p>No matches!</p>");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement