Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.notsocomplex.regex;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import org.junit.Assert;
- import org.junit.Test;
- public class RegexReplaceGroupTest {
- @Test
- public void testReplacementWithGroupsSingleMatch() {
- String text = "Frank Castle is Spider-Man. No Really!";
- // Group 1: (.+\\Wis\\W)
- // -Match any character 1 or more time
- // -Followed by 'is'
- // -Followed by non-word boundary
- // Group 2: (.+)
- // -Match any character 1 or more time
- // Group 3: (\\..+)
- // -Match the dot character followed by 1 or more character
- String regex = "(.+is\\W)(.+)(\\..+)";
- Pattern pattern = Pattern.compile(regex);
- Matcher matcher = pattern.matcher(text);
- // Make sure we have a match. This matches the entire input.
- Assert.assertTrue(matcher.find());
- // 3 groups are created
- Assert.assertEquals("Frank Castle is ", matcher.group(1));
- Assert.assertEquals("Spider-Man", matcher.group(2));
- Assert.assertEquals(". No Really!", matcher.group(3));
- // Replace the match (which is the entire input!) by the group at position 1, the literal
- // string 'The Punisher' and the group at position 3
- String replaced = matcher.replaceAll("$1The Punisher$3");
- Assert.assertEquals("Frank Castle is The Punisher. No Really!", replaced);
- // Also works with replaceFirst, since we have a single match
- replaced = matcher.replaceFirst("$1The Punisher$3");
- Assert.assertEquals("Frank Castle is The Punisher. No Really!", replaced);
- // Lets reset the matcher and use appendReplacement instead to replace the individual groups
- matcher.reset();
- matcher.matches();
- // Replace the match, which is everything, by group 1, 'The Punisher' and group 3
- StringBuffer buffer = new StringBuffer();
- matcher.appendReplacement(buffer, "$1The Punisher$3");
- Assert.assertEquals("Frank Castle is The Punisher. No Really!", buffer.toString());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement