Skip to content

Commit 3dca523

Browse files
hsudhofcopybara-github
authored andcommitted
Add re2 quote method for escaping literal patterns
PiperOrigin-RevId: 574927386 Change-Id: Id95fc3f7bbc3da7f4fda06fbdc5b2ed3e4c21ef7
1 parent 12a8283 commit 3dca523

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

docs/reference.md

+15
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@
195195
- [PathAttributes](#pathattributes)
196196
- [re2](#re2)
197197
- [re2.compile](#re2compile)
198+
- [re2.quote](#re2quote)
198199
- [re2_matcher](#re2_matcher)
199200
- [re2_matcher.end](#re2_matcherend)
200201
- [re2_matcher.find](#re2_matcherfind)
@@ -4762,6 +4763,20 @@ re2.compile("a(.*)b").matches('accccb')
47624763
```
47634764

47644765

4766+
<a id="re2.quote" aria-hidden="true"></a>
4767+
### re2.quote
4768+
4769+
Quote a string to be matched literally if used within a regex pattern
4770+
4771+
`string` `re2.quote(string)`
4772+
4773+
4774+
#### Parameters:
4775+
4776+
Parameter | Description
4777+
--------- | -----------
4778+
string | `string`<br><p></p>
4779+
47654780

47664781

47674782
## re2_matcher

java/com/google/copybara/re2/Re2Module.java

+9
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,13 @@ public class Re2Module implements StarlarkValue {
3838
public StarlarkPattern compile(String regex) {
3939
return new StarlarkPattern(Pattern.compile(regex));
4040
}
41+
42+
@StarlarkMethod(
43+
name = "quote",
44+
doc = "Quote a string to be matched literally if used within a regex pattern",
45+
parameters = {
46+
@Param(name = "string")})
47+
public String quote(String string) {
48+
return Pattern.quote(string);
49+
}
4150
}

javatests/com/google/copybara/re2/Re2Test.java

+10
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,14 @@ public void replaceAllParam() throws ValidationException {
184184
+ "m.matches()\n"
185185
+ "x = m.replace_all('HELLO$1')")).isEqualTo("HELLObbHELLObbb");
186186
}
187+
188+
@Test
189+
public void quoteQuotes() throws ValidationException {
190+
assertThat(skylark.<Boolean>eval("x", ""
191+
+ "re = re2.compile('a%s' % (re2.quote('.*')))\n"
192+
+ "x = re.matcher('axxxxxb').matches()\n")).isFalse();
193+
assertThat(skylark.<Boolean>eval("x", ""
194+
+ "re = re2.compile('a%s' % (re2.quote('.*')))\n"
195+
+ "x = re.matcher('a.*').matches()\n")).isTrue();
196+
}
187197
}

0 commit comments

Comments
 (0)