thufir

regex last word

Sep 12th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.73 KB | None | 0 0
  1. package regex;
  2.  
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. public class Main {
  7.  
  8.     public static void main(String[] args) {
  9.         String matchesLastWordFine = "a b cd efg hi";
  10.         lastWord(matchesLastWordFine);
  11.         String noMatchFound = matchesLastWordFine + ".";
  12.         lastWord(noMatchFound);
  13.     }
  14.  
  15.     private static void lastWord(String sentence) {
  16.         System.out.println("\n\ntrying\n" + sentence + "\nmatches:");
  17.         Pattern pattern = Pattern.compile("(\\w+)$");
  18.         Matcher matcher = pattern.matcher(sentence);
  19.         String match = null;
  20.         while (matcher.find()) {
  21.             match = matcher.group();
  22.             System.out.println(match);
  23.         }
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment