Advertisement
dimipan80

Java Regex: Sentence Extractor

Aug 2nd, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. /*
  2. * Write a program that reads a keyword and some text from the console and prints all sentences from the text, containing that word.
  3. * A sentence is any sequence of words:
  4. *   ending with dot ('.'), exclamation mark ('!') or question mark ('?').
  5. */
  6.  
  7.  
  8. import java.io.BufferedReader;
  9. import java.io.IOException;
  10. import java.io.InputStreamReader;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13.  
  14. public class SentenceExtractor {
  15.     public static void main(String[] args) {
  16.         String keyword = "";
  17.         String text = "";
  18.  
  19.         try {
  20.             BufferedReader reader =
  21.                     new BufferedReader(new InputStreamReader(System.in));
  22.  
  23.             keyword = reader.readLine();
  24.             text = reader.readLine();
  25.         } catch (IOException e) {
  26.             e.printStackTrace();
  27.         }
  28.  
  29.         String patternStr = String.format("\\b[A-Z][^.?!]*?\\b%s\\b.*?[!.?]", keyword);
  30.         Pattern pattern = Pattern.compile(patternStr);
  31.         Matcher matcher = pattern.matcher(text);
  32.         while (matcher.find()) {
  33.             System.out.println(matcher.group());
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement