Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -78,7 +78,7 @@ enum Function {
String pattern = (String) args[1];
String replaceStr = (String) args[2];
long count = (long) args[3];
return CelRegexExtensions.replace(target, pattern, replaceStr, count);
return CelRegexExtensions.replaceN(target, pattern, replaceStr, count);
}))),
EXTRACT(
CelFunctionDecl.newFunctionDeclaration(
Expand DownExpand Up@@ -153,18 +153,20 @@ private static Pattern compileRegexPattern(String regex) {
}

private static String replace(String target, String regex, String replaceStr) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
return matcher.replaceAll(replaceStr);
return replaceN(target, regex, replaceStr, -1);
}

private static String replace(String target, String regex, String replaceStr, long replaceCount) {
Pattern pattern = compileRegexPattern(regex);

private static String replaceN(
String target, String regex, String replaceStr, long replaceCount) {
if (replaceCount == 0) {
return target;
}
// For all negative replaceCount, do a replaceAll
if (replaceCount < 0) {
replaceCount = -1;
}

Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
StringBuffer sb = new StringBuffer();
int counter = 0;
Expand All@@ -173,14 +175,59 @@ private static String replace(String target, String regex, String replaceStr, lo
if (replaceCount != -1 && counter >= replaceCount) {
break;
}
matcher.appendReplacement(sb, replaceStr);

String processedReplacement = replaceStrValidator(matcher, replaceStr);
matcher.appendReplacement(sb, Matcher.quoteReplacement(processedReplacement));
counter++;
}
matcher.appendTail(sb);

return sb.toString();
}

private static String replaceStrValidator(Matcher matcher, String replacement) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);

if (c != '\\') {
sb.append(c);
continue;
}

if (i + 1 >= replacement.length()) {
throw new IllegalArgumentException("Invalid replacement string: \\ not allowed at end");
}

char nextChar = replacement.charAt(++i);

if (Character.isDigit(nextChar)) {
int groupNum = Character.digit(nextChar, 10);
int groupCount = matcher.groupCount();

if (groupNum > groupCount) {
throw new IllegalArgumentException(
"Replacement string references group "
+ groupNum
+ " but regex has only "
+ groupCount
+ " group(s)");
}

String groupValue = matcher.group(groupNum);
if (groupValue != null) {
sb.append(groupValue);
}
} else if (nextChar == '\\') {
sb.append('\\');
} else {
throw new IllegalArgumentException(
"Invalid replacement string: \\ must be followed by a digit");
}
}
return sb.toString();
}

private static Optional<String> extract(String target, String regex) {
Pattern pattern = compileRegexPattern(regex);
Matcher matcher = pattern.matcher(target);
Expand DownExpand Up@@ -215,11 +262,12 @@ private static ImmutableList<String> extractAll(String target, String regex) {
while (matcher.find()) {
if (hasOneGroup) {
String group = matcher.group(1);
// Add the captured group's content only if it's not null (e.g. optional group didn't match)
// Add the captured group's content only if it's not null
if (group != null) {
builder.add(group);
}
} else { // No capturing groups (matcher.groupCount() == 0)
} else {
// No capturing groups
builder.add(matcher.group(0));
}
}
Expand Down
21 changes: 13 additions & 8 deletions extensions/src/main/java/dev/cel/extensions/README.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -717,12 +717,15 @@ chance for collision.

### Replace

The `regex.replace` function replaces all occurrences of a regex pattern in a
string with a replacement string. Optionally, you can limit the number of
replacements by providing a count argument. Both numeric ($N) and named
(${name}) capture group references are supported in the replacement string, with
validation for correctness. An error will be thrown for invalid regex or replace
string.
The `regex.replace` function replaces all non-overlapping substring of a regex
pattern in the target string with a replacement string. Optionally, you can
limit the number of replacements by providing a count argument. When the count
is a negative number, the function acts as replace all. Only numeric (\N)
capture group references are supported in the replacement string, with
validation for correctness. Backslashed-escaped digits (\1 to \9) within the
replacement argument can be used to insert text matching the corresponding
parenthesized group in the regexp pattern. An error will be thrown for invalid
regex or replace string.

```
regex.replace(target: string, pattern: string, replacement: string) -> string
Expand All@@ -732,14 +735,16 @@ regex.replace(target: string, pattern: string, replacement: string, count: int)
Examples:

```
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
regex.replace('banana', 'a', 'x', 0) == 'banana'
regex.replace('banana', 'a', 'x', 1) == 'bxnana'
regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
regex.replace('foo bar', '(fo)o (ba)r', '$2 $1') == 'ba fo'
regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
regex.replace('foo bar', '(fo)o (ba)r', '\\2 \\1') == 'ba fo'

regex.replace('test', '(.)', '$2') \\ Runtime Error invalid replace string
regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: ${values}') \\ Runtime Error invalid replace string
regex.replace('id=123', 'id=(?P<value>\\\\d+)', 'value: \\values') \\ Runtime Error invalid replace string

```

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,23 +39,31 @@ public final class CelRegexExtensionsTest {
CelRuntimeFactory.standardCelRuntimeBuilder().addLibraries(CelExtensions.regex()).build();

@Test
@TestParameters("{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '$2 $1', res: 'ba fo'}")
@TestParameters("{target: 'abc', regex: '^', replaceStr: 'start_', res: 'start_abc'}")
@TestParameters("{target: 'abc', regex: '$', replaceStr: '_end', res: 'abc_end'}")
@TestParameters("{target: 'a-b', regex: '\\\\b', replaceStr: '|', res: '|a|-|b|'}")
@TestParameters(
"{target: 'foo bar', regex: '(fo)o (ba)r', replaceStr: '\\\\2 \\\\1', res: 'ba fo'}")
@TestParameters("{target: 'foo bar', regex: 'foo', replaceStr: '\\\\\\\\', res: '\\ bar'}")
@TestParameters("{target: 'banana', regex: 'ana', replaceStr: 'x', res: 'bxna'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x$1', res: 'axc'}")
@TestParameters("{target: 'abc', regex: 'b(.)', replaceStr: 'x\\\\1', res: 'axc'}")
@TestParameters(
"{target: 'hello world hello', regex: 'hello', replaceStr: 'hi', res: 'hi world hi'}")
@TestParameters("{target: 'ac', regex: 'a(b)?c', replaceStr: '[\\\\1]', res: '[]'}")
@TestParameters("{target: 'apple pie', regex: 'p', replaceStr: 'X', res: 'aXXle Xie'}")
@TestParameters(
"{target: 'remove all spaces', regex: '\\\\s', replaceStr: '', res: 'removeallspaces'}")
@TestParameters("{target: 'digit:99919291992', regex: '\\\\d+', replaceStr: '3', res: 'digit:3'}")
@TestParameters(
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '($0)', res: '(foo) (bar) (baz)'}")
"{target: 'foo bar baz', regex: '\\\\w+', replaceStr: '(\\\\0)', res: '(foo) (bar) (baz)'}")
@TestParameters("{target: '', regex: 'a', replaceStr: 'b', res: ''}")
@TestParameters(
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '${name} is ${age} years old', res: 'Alice is 30 years old'}")
+ " replaceStr: '${name} is ${age} years old', res: '${name} is ${age} years old'}")
@TestParameters(
"{target: 'abc', regex: '(?P<letter>b)', replaceStr: '[${letter}]', res: 'a[b]c'}")
"{target: 'User: Alice, Age: 30', regex: 'User: (?P<name>\\\\w+), Age: (?P<age>\\\\d+)',"
+ " replaceStr: '\\\\1 is \\\\2 years old', res: 'Alice is 30 years old'}")
@TestParameters("{target: 'hello ☃', regex: '☃', replaceStr: '❄', res: 'hello ❄'}")
public void replaceAll_success(String target, String regex, String replaceStr, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
Expand All@@ -70,8 +78,8 @@ public void replaceAll_success(String target, String regex, String replaceStr, S
public void replace_nested_success() throws Exception {
String expr =
"regex.replace("
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','\\\\${$1}'),"
+ " '%(\\\\d+)', '\\\\$$1')";
+ " regex.replace('%(foo) %(bar) %2','%\\\\((\\\\w+)\\\\)','${\\\\1}'),"
+ " '%(\\\\d+)', '$\\\\1')";
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -85,19 +93,18 @@ public void replace_nested_success() throws Exception {
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 2, res: 'bxnxna'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: 100, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -1, res: 'bxnxnx'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'banana'}")
@TestParameters("{t: 'banana', re: 'a', rep: 'x', i: -100, res: 'bxnxnx'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 1,"
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 1,"
+ " res: 'dog-cat dog-cat cat-dog dog-cat'}")
@TestParameters(
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '$2-$1', i: 2, res: 'dog-cat"
+ " dog-cat dog-cat dog-cat'}")
"{t: 'cat-dog dog-cat cat-dog dog-cat', re: '(cat)-(dog)', rep: '\\\\2-\\\\1', i: 2, res:"
+ " 'dog-cat dog-cat dog-cat dog-cat'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: 1, res: 'a-b.c'}")
@TestParameters("{t: 'a.b.c', re: '\\\\.', rep: '-', i: -1, res: 'a-b-c'}")
public void replaceCount_success(String t, String re, String rep, long i, String res)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s', %d)", t, re, rep, i);
System.out.println("expr: " + expr);
CelRuntime.Program program = RUNTIME.createProgram(COMPILER.compile(expr).getAst());

Object result = program.eval();
Expand All@@ -108,7 +115,7 @@ public void replaceCount_success(String t, String re, String rep, long i, String
@Test
@TestParameters("{target: 'foo bar', regex: '(', replaceStr: '$2 $1'}")
@TestParameters("{target: 'foo bar', regex: '[a-z', replaceStr: '$2 $1'}")
public void replace_invalid_regex(String target, String regex, String replaceStr)
public void replace_invalidRegex_throwsException(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();
Expand All@@ -121,32 +128,48 @@ public void replace_invalid_regex(String target, String regex, String replaceStr
}

@Test
@TestParameters("{target: 'test', regex: '(.)', replaceStr: '$2'}")
public void replace_invalid_captureGroup(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_invalidCaptureGroupReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('test', '(.)', '\\\\2')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("n > number of groups");
assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Replacement string references group 2 but regex has only 1 group(s)");
}

@Test
@TestParameters(
"{target: 'id=123', regex: 'id=(?P<value>\\\\d+)', replaceStr: 'value: ${values}'}")
public void replace_invalid_replaceStr(String target, String regex, String replaceStr)
throws Exception {
String expr = String.format("regex.replace('%s', '%s', '%s')", target, regex, replaceStr);
public void replace_trailingBackslashReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ not allowed at end");
}

@Test
public void replace_invalidGroupReferenceReplaceStr_throwsException() throws Exception {
String expr = "regex.replace('id=123', 'id=(?P<value>\\\\d+)', '\\\\a')";
CelAbstractSyntaxTree ast = COMPILER.compile(expr).getAst();

CelEvaluationException e =
assertThrows(CelEvaluationException.class, () -> RUNTIME.createProgram(ast).eval());

assertThat(e).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(e).hasCauseThat().hasMessageThat().contains("group 'values' not found");
assertThat(e)
.hasCauseThat()
.hasMessageThat()
.contains("Invalid replacement string: \\ must be followed by a digit");
}

@Test
Expand DownExpand Up@@ -208,6 +231,9 @@ private enum ExtractAllTestCase {
NO_MATCH("regex.extractAll('id:123, id:456', 'assa')", ImmutableList.of()),
NO_CAPTURE_GROUP(
"regex.extractAll('id:123, id:456', 'id:\\\\d+')", ImmutableList.of("id:123", "id:456")),
CAPTURE_GROUP(
"regex.extractAll('key=\"\", key=\"val\"', 'key=\"([^\"]*)\"')",
ImmutableList.of("", "val")),
SINGLE_NAMED_GROUP(
"regex.extractAll('testuser@testdomain', '(?P<username>.*)@')",
ImmutableList.of("testuser")),
Expand Down