Advertisement
Guest User

Untitled

a guest
May 24th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 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. @Test
  12. public void testReplacementWithGroupsSingleMatch() {
  13.  
  14. String text = "Frank Castle is Spider-Man. No Really!";
  15.  
  16. // Group 1: (.+\\Wis\\W)
  17. // -Match any character 1 or more time
  18. // -Followed by 'is'
  19. // -Followed by non-word boundary
  20. // Group 2: (.+)
  21. // -Match any character 1 or more time
  22. // Group 3: (\\..+)
  23. // -Match the dot character followed by 1 or more character
  24. String regex = "(.+is\\W)(.+)(\\..+)";
  25.  
  26. Pattern pattern = Pattern.compile(regex);
  27. Matcher matcher = pattern.matcher(text);
  28.  
  29. // Make sure we have a match. This matches the entire input.
  30. Assert.assertTrue(matcher.find());
  31.  
  32. // 3 groups are created
  33. Assert.assertEquals("Frank Castle is ", matcher.group(1));
  34. Assert.assertEquals("Spider-Man", matcher.group(2));
  35. Assert.assertEquals(". No Really!", matcher.group(3));
  36.  
  37. // Replace the match (which is the entire input!) by the group at position 1, the literal
  38. // string 'The Punisher' and the group at position 3
  39. String replaced = matcher.replaceAll("$1The Punisher$3");
  40. Assert.assertEquals("Frank Castle is The Punisher. No Really!", replaced);
  41.  
  42. // Also works with replaceFirst, since we have a single match
  43. replaced = matcher.replaceFirst("$1The Punisher$3");
  44. Assert.assertEquals("Frank Castle is The Punisher. No Really!", replaced);
  45.  
  46. // Lets reset the matcher and use appendReplacement instead to replace the individual groups
  47. matcher.reset();
  48. matcher.matches();
  49.  
  50. // Replace the match, which is everything, by group 1, 'The Punisher' and group 3
  51. StringBuffer buffer = new StringBuffer();
  52. matcher.appendReplacement(buffer, "$1The Punisher$3");
  53. Assert.assertEquals("Frank Castle is The Punisher. No Really!", buffer.toString());
  54.  
  55. }
  56.  
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement