Skip to content

Commit 144c8a8

Browse files
committed
✨ Support backreferences on regex substitution
Reference #361
1 parent 92709dc commit 144c8a8

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/script/lib/filter.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,16 @@ export default class Filter {
141141
if (this.checkWhitelist(match, string, matchStartIndex, word)) { return match; } // Check for whitelisted match
142142
if (statsType) { this.foundMatch(word, statsType); }
143143

144+
// Support backreferences for REGEX match method (only checks for 1 capture group)
145+
if (word.matchMethod == Constants.MATCH_METHODS.REGEX && captureGroups.length && word.sub.includes('\\1')) {
146+
let sub = word.sub;
147+
captureGroups.forEach((captureGroup, i) => { sub = sub.replace(`\\${i + 1}`, captureGroup); });
148+
if (sub !== word.sub) {
149+
// Only return if something was substituted
150+
return sub;
151+
}
152+
}
153+
144154
// Filter
145155
let sub = word.sub || this.cfg.defaultSubstitution;
146156

test/lib/filter.spec.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,16 @@ describe('Filter', () => {
386386
filter.init();
387387
expect(filter.replaceText('Have you ever been cut by a Cat?')).to.equal('Have you ever been bit by a Bit?');
388388
});
389+
390+
it('Should support backreferences in replace', () => {
391+
const filter = new Filter;
392+
filter.cfg = new Config({ words: Object.assign({}, testWords), filterMethod: Constants.FILTER_METHODS.SUBSTITUTE });
393+
filter.cfg.words['pee([ed]{0,2}[ ]?\\w*?) off'] = { matchMethod: Constants.MATCH_METHODS.REGEX, repeat: Constants.FALSE, sub: 'tick\\1 off' };
394+
filter.cfg.words['scare([ ]?\\w*) off'] = { matchMethod: Constants.MATCH_METHODS.REGEX, repeat: Constants.FALSE, sub: 'spook\\1 off' };
395+
filter.init();
396+
expect(filter.replaceText('Try not to pee John off.')).to.equal('Try not to tick John off.');
397+
expect(filter.replaceText('Try not to scare John off.')).to.equal('Try not to spook John off.');
398+
});
389399
});
390400

391401
describe('whitelist', () => {

0 commit comments

Comments
 (0)