Skip to content

Commit 6ccd2ac

Browse files
committed
Added regex_count function
1 parent b15f112 commit 6ccd2ac

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,21 @@ regex_replace('/world/', 'universe', 'hello world')
412412
// "hello universe"
413413
```
414414
415+
### `regex_count`
416+
**Syntax**:
417+
```jmespath
418+
regex_count(regex, string)
419+
```
420+
421+
**Description**:
422+
Counts the number of matches of a regular expression in a string.
423+
424+
**Example**:
425+
```jmespath
426+
regex_count('/\\w+/g', 'hello world')
427+
// 2
428+
```
429+
415430
## More Resources
416431
417432
The example above only shows a small amount of what

src/Runtime.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,10 @@ export class Runtime {
710710
return val.replace(this.parseRegexString(regexp), repl);
711711
};
712712

713+
private functionRegexCount: RuntimeFunction<[string, string], number> = ([regexp, val]) => {
714+
return Array.from(val.matchAll(this.parseRegexString(regexp))).length;
715+
};
716+
713717
private functionTable: FunctionTable = {
714718
abs: {
715719
_func: this.functionAbs,
@@ -1272,5 +1276,16 @@ export class Runtime {
12721276
},
12731277
],
12741278
},
1279+
regex_count: {
1280+
_func: this.functionRegexCount,
1281+
_signature: [
1282+
{
1283+
types: [InputArgument.TYPE_STRING],
1284+
},
1285+
{
1286+
types: [InputArgument.TYPE_STRING],
1287+
},
1288+
],
1289+
},
12751290
};
12761291
}

test/jmespath-functions.spec.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,10 @@ describe('Added functions', () => {
210210
expect(search('hello world', "regex_replace('/w\\w+d/', 'planet', @)")).toEqual('hello planet');
211211
expect(search('hello world', "regex_replace('/[aeoiu]/g', '*', @)")).toEqual('h*ll* w*rld');
212212
});
213+
214+
it('regex_count', () => {
215+
expect(search('hello world', "regex_count('/\\w+/g', @)")).toEqual(2);
216+
});
213217
});
214218

215219
describe('custom functions', () => {

0 commit comments

Comments
 (0)