Advertisement
dimipan80

Regex: Replace <a> Tag

Aug 2nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. /*
  2.     You are given an HTML document given as a string on multiple lines.
  3.     Write a program that replaces all the tags <a href=…>…</a> with corresponding tags [URL href=…]…[/URL].
  4.     Read lines until you get the "END" command.
  5.     Note: a tag can start and end on different lines, but actual keywords like "href=" or the closing tag "</a>" will never be split.
  6.     For example, you will never get:
  7.         <a hr
  8.         ef="http://softuni.bg">SoftUni</
  9.         a>
  10.  
  11.     Hints
  12.     • Use a string builder to read the whole input into a single string. Make sure to save the new lines.
  13.     • Create a pattern that can match a valid tag on multiple lines. Note that href= and </a> will never be split.
  14.     • Use a string builder to replace all matches.
  15.  
  16.     Examples:
  17.         <ul> <li> <a                                                                <ul> <li> [URL href="http://softuni.bg"]SoftUni[/URL]
  18.         href="http://softuni.bg">SoftUni</a>                 ->                      </li> </ul>
  19.          </li> </ul>
  20.         END
  21.  
  22.         <a href="/">                                                                [URL href="/"]
  23.         Link</a>                                            ->                      Link[/URL]
  24.         END
  25. */
  26.  
  27. import java.io.BufferedReader;
  28. import java.io.IOException;
  29. import java.io.InputStreamReader;
  30.  
  31. public class ReplaceA_Tag {
  32.     public static void main(String[] args) {
  33.         StringBuilder htmlText = new StringBuilder();
  34.  
  35.         try (BufferedReader reader =
  36.                      new BufferedReader(new InputStreamReader(System.in))) {
  37.  
  38.             String inputLine = reader.readLine();
  39.             while (!inputLine.equals("END")) {
  40.                 htmlText.append(inputLine).append(System.lineSeparator());
  41.  
  42.                 inputLine = reader.readLine();
  43.             }
  44.  
  45.         } catch (IOException e) {
  46.             e.printStackTrace();
  47.         }
  48.  
  49.         String output = htmlText.toString()
  50.                 .replaceAll("<a\\s([^>]+)>([^<]+)</a>", "[URL $1]$2[/URL]");
  51.  
  52.         System.out.println(output);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement