martyychang

StringUtil.isolateFirst(String, String)

Feb 15th, 2014
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. /*
  2.  * Utility class providing additional methods useful for string manipulation
  3.  *
  4.  * @version 0.1
  5.  * @author  Marty Chang (Slalom Consulting)
  6.  */
  7. public class StringUtil {
  8.    
  9.     /*
  10.      * @param  haystack The string
  11.      * @param  regExp   The regular expression
  12.      * @return The first substring of the string that matches the regular
  13.      *         expression; <code>null</code> otherwise
  14.      */
  15.     public static String isolateFirst(String haystack, String regExp) {
  16.         String match = null;
  17.  
  18.         // Attempt to split the haystack using the regular expression.
  19.         // If the split successfully produces two "ends", use the
  20.         // info about the ends to extract the match in the middle
  21.  
  22.         List<String> haystackEnds = haystack.split(regExp, 2);
  23.  
  24.         if (haystackEnds.size() == 2) {
  25.             String frontEnd = haystackEnds.get(0);
  26.             String backEnd = haystackEnds.get(1);
  27.  
  28.             match = haystack.substring(frontEnd.length(),
  29.                 haystack.length() - backEnd.length());
  30.         }
  31.  
  32.         // Return the match
  33.  
  34.         return match;
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment