Advertisement
Guest User

Untitled

a guest
May 23rd, 2015
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. package com.notsocomplex.regex;
  2.  
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. import org.junit.Assert;
  7. import org.junit.Test;
  8.  
  9. public class RegexReplaceGroupTest {
  10.  
  11.  
  12. @Test
  13. public void testReplacementWithGroupsMultipleMatches() {
  14.  
  15. String text =
  16. "this sentence should start with a capital letter. this one also! "
  17. + "what about this one? Or this one?";
  18.  
  19. // Group 1: ([a-z])
  20. // -Match a character, create a group (1)
  21. // Group 2: (.+?[.!?])
  22. // -Match anything one or more time
  23. // -Make the match non-greedy, so stop the match when minimum is reached
  24. // -Followed by one of these character .!?. Could have used \p{Punct} also.
  25. String regex = "([a-z])(.+?[.!?])";
  26.  
  27. // Enable case-insensitive in Java is done using flags from Pattern.
  28. // Without this flag, we would have needed [a-zA-z] in our first group.
  29. Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
  30. Matcher matcher = pattern.matcher(text);
  31.  
  32. StringBuffer sb = new StringBuffer();
  33.  
  34. // For each match. There will be 4, one for each sentence
  35. while (matcher.find()) {
  36.  
  37. // Get the first group, which is the first letter of the sentence. Matched by the ([a-z]).
  38. String firstLetter = matcher.group(1);
  39.  
  40. // Replace the match from the beginning with the upper case value
  41. // of the first letter and the group with at position 2
  42. matcher.appendReplacement(sb, firstLetter.toUpperCase() + "$2");
  43.  
  44. }
  45.  
  46. // Append the tail, there should be none but it is always safer to
  47. // do this
  48. matcher.appendTail(sb);
  49. Assert.assertEquals(sb.toString(), "This sentence should start with a capital letter. This one also! What about this one? Or this one?");
  50.  
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement