add ReplaceAll, ReplaceRegex binding functions

This commit is contained in:
Jonathan Shook 2021-02-05 14:42:31 -06:00
parent 68c4565e75
commit c6f09f3e87
3 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package io.nosqlbench.virtdata.library.basics.shared.unary_string;
import io.nosqlbench.virtdata.api.annotations.Example;
import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper;
import java.util.function.Function;
/**
* Replace all occurrences of the extant string with the replacement string.
*/
@ThreadSafeMapper
public class ReplaceAll implements Function<String, String> {
private final String extant;
private final String replacement;
@Example({"ReplaceAll('one','two')", "Replace all occurrences of 'one' with 'two'"})
public ReplaceAll(String extant, String replacement) {
this.extant = extant;
this.replacement = replacement;
}
@Override
public String apply(String s) {
return s.replaceAll(extant, replacement);
}
}

View File

@ -0,0 +1,36 @@
package io.nosqlbench.virtdata.library.basics.shared.unary_string;
import io.nosqlbench.virtdata.api.annotations.Example;
import io.nosqlbench.virtdata.api.annotations.ThreadSafeMapper;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Replace all occurrences of the regular expression with the replacement string.
* Note, this is much less efficient than using the simple ReplaceAll for most cases.
*/
@ThreadSafeMapper
public class ReplaceRegex implements Function<String, String> {
private final String replacement;
private final Pattern pattern;
@Example({"ReplaceRegex('[one]','two')", "Replace all occurrences of 'o' or 'n' or 'e' with 'two'"})
public ReplaceRegex(String regex, String replacement) {
this.pattern = Pattern.compile(regex);
this.replacement = replacement;
}
@Override
public String apply(String s) {
Matcher matcher = pattern.matcher(s);
StringBuilder sb = new StringBuilder(s.length());
while (matcher.find()) {
matcher.appendReplacement(sb, replacement);
}
matcher.appendTail(sb);
return sb.toString();
}
}

View File

@ -0,0 +1,24 @@
package io.nosqlbench.virtdata.library.basics.shared.unary_string;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ReplaceRegexTest {
@Test
public void testRegexReplacer() {
ReplaceRegex two = new ReplaceRegex("[one]", "two");
String replaced = two.apply("one");
assertThat(replaced).isEqualTo("twotwotwo");
}
@Test
public void testReplaceString() {
ReplaceAll replaceAll = new ReplaceAll("one", "two");
String replaced = replaceAll.apply("onetwothree");
assertThat(replaced).isEqualTo("twotwothree");
}
}