Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package javax0.j9regex.samples;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
public class NewMatcherMethods {
@Test
public void demoReplaceAllFunction() {
Pattern pattern = Pattern.compile("dog");
Matcher matcher = pattern.matcher("zzzdogzzzdogzzz");
String result = matcher.replaceAll(mr -> mr.group().toUpperCase());
assertEquals("zzzDOGzzzDOGzzz", result);
}
@Test
public void countSampleReplaceAllFunction() {
//Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(?:[Ee][+-]?\\d{1,2})?");
AtomicInteger counter = new AtomicInteger(0);
Pattern pattern = Pattern.compile("#+");
Matcher matcher = pattern.matcher("# first item\n" +
"# second item\n" +
"## third and fourth\n" +
"## item 5 and 6\n" +
"# item 7");
String result = matcher.replaceAll(mr -> "" + counter.addAndGet(mr.group().length()));
assertEquals("1 first item\n" +
"2 second item\n" +
"4 third and fourth\n" +
"6 item 5 and 6\n" +
"7 item 7", result);
}
@Test
public void calculateSampleReplaceAllFunction() {
Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(?:[Ee][+-]?\\d{1,2})?");
Matcher matcher = pattern.matcher("The sin(pi) is 3.1415926");
String result = matcher.replaceAll(mr -> "" + (Math.sin(Double.parseDouble(mr.group()))));
assertEquals("The sin(pi) is 5.3589793170057245E-8", result);
}
@Test
public void resultsTest() {
Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(?:[Ee][+-]?\\d{1,2})?");
Matcher matcher = pattern.matcher("Pi is around 3.1415926 and not 3.2 even in Indiana");
String result = String.join(",",
matcher
.results()
.map(mr -> "" + (Math.sin(Double.parseDouble(mr.group()))))
.collect(Collectors.toList()));
assertEquals("5.3589793170057245E-8,-0.058374143427580086", result);
}
@Test
public void testAppendReplacement() {
Pattern p = Pattern.compile("cat(?<plural>z?s?)");
//Pattern p = Pattern.compile("cat(z?s?)");
Matcher m = p.matcher("one catz two cats in the yard");
StringBuilder sb = new StringBuilder();
while (m.find()) {
m.appendReplacement(sb, "dog${plural}");
//m.appendReplacement(sb, "dog$001");
}
m.appendTail(sb);
String result = sb.toString();
assertEquals("one dogz two dogs in the yard", result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.