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 testReplacementWithGroupsMultipleMatches() {
- String text =
- "this sentence should start with a capital letter. this one also! "
- + "what about this one? Or this one?";
- // Group 1: ([a-z])
- // -Match a character, create a group (1)
- // Group 2: (.+?[.!?])
- // -Match anything one or more time
- // -Make the match non-greedy, so stop the match when minimum is reached
- // -Followed by one of these character .!?. Could have used \p{Punct} also.
- String regex = "([a-z])(.+?[.!?])";
- // Enable case-insensitive in Java is done using flags from Pattern.
- // Without this flag, we would have needed [a-zA-z] in our first group.
- Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
- Matcher matcher = pattern.matcher(text);
- StringBuffer sb = new StringBuffer();
- // For each match. There will be 4, one for each sentence
- while (matcher.find()) {
- // Get the first group, which is the first letter of the sentence. Matched by the ([a-z]).
- String firstLetter = matcher.group(1);
- // Replace the match from the beginning with the upper case value
- // of the first letter and the group with at position 2
- matcher.appendReplacement(sb, firstLetter.toUpperCase() + "$2");
- }
- // Append the tail, there should be none but it is always safer to
- // do this
- matcher.appendTail(sb);
- Assert.assertEquals(sb.toString(), "This sentence should start with a capital letter. This one also! What about this one? Or this one?");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement